MongoDB and PHP: An Intermediate Tutorial

MongoDB is an exciting and (relatively) new database technology that’s gaining popularity among developers. And odds are you’re here for one of two reasons:

  1. You want to practice using MongoDB in a PHP environment
  2. You got lost on the Internet and don’t know why you’re here

If you’re here for reason number 1 then you’re in luck because I happen to have an intermediate level tutorial all prepared that will take you step by step through the process of designing and coding a MongoDB web application.

Part 1: Introduction

Part 2: Project Design

Part 3: Getting Familiar With MongoDB

Part 4: Reading The Database With PHP

Part 5: Sorting Data

Part 6: Finding One Unique Document

Part 6.5: Fixing itemView.php

Part 7: User Friendly Data Input

Part 8: Deleting Items

Part 9: Final Feature Is Search

Download Complete Tutorial Code

I strongly suggest following the tutorials and writing your own code as you go. But I’ve also included a complete copy of the project’s code if you need a reference or are having trouble getting a particular bit of code to work. As long as you have properly configured your server and PHP environment to work with MongoDB you should be able to just drop these files into a server directory and watch it work.

mongodbtutorialcode

MongoDB Tutorial Part 9: Final Feature Is Search

Now Where Did I Put That Wand…

 

Way back in tutorial 3 we talked about how to use find and the command line tool to search for entire groups of items inside a collection. Now we’re going to do the same thing with PHP and connect it all to a user friendly form that makes searching for treasure as easy as clicking a button. This is the last major feature of Treasure Bag. After this we’ll be done and you will have successfully built a complete MongoDB web application.

 

Bad Design Warning

 

We’re going to create the treasure search form by copy pasting and then slightly modifying the JavaScript and HTML from the treasure creation form. And in order to print our search results we’re going to copy paste the treasure listing code from “index.php”.

 

In a big, professional project duplicating code like this is a major mistake. Duplicating code means you risk duplicating bugs. And even if you don’t accidentally copy and paste a bug all over your code you might decide you need to upgrade your program and now you’re stuck finding and rewriting every piece of duplicate code.

 

If you find yourself copy pasting a certain bit of code it’s usually a better idea to turn that code into a function or a class that only has to be written once but can be used by multiple files. Then fixing bugs and making upgrades is as simple as updating one piece of code.

 

But this isn’t a big, professional project. It’s just a tiny practice project and we’re not concerned about security bugs or clients demanding new features. So in this case we can get away with being a little sloppy and copy pasting a bit.

 

Just don’t let me catch you doing it anywhere else.

 

Creating The Search Form

 

Our search form is going to be called “search.php” and will be made up of two halves. The first half of the file will be a JavaScipt enhanced HTML form that lets the user tell us what he is searching for. The second half of the file will be a PHP script that takes the user’s treasure requirements, finds any items that match and then prints them to the screen.

 

Let’s start by creating a new “search.php” file. Since this is a MongoDB tutorial I’m just going to dump the boring form code on you with minimal explanation. It’s virtually identical to the treasure creation form in “add.php” with only three slight difference.

 

First, inputs that expect numbers have been split into a Max and Min field. So instead of just asking the user for “Price” they will be asked for “Max Price” and “Min Price”.

 

Second, the form is now of type “GET” instead of “POST”.

 

Third, the drop down value for not selecting a treasure type is now the empty string ” instead of ‘none’. As you read the rest of the code I’m sure you’ll be able to figure out why we made these changes.

 

<?php
include('header.php');
?>
<script>
	function addTypeSpecificAttributes(){
		var specificAttributesDiv =  document.getElementById('typeSpecificAttributesDiv');
		var typeSelect = document.getElementById('typeSelect');
		var currentType = typeSelect.options[typeSelect.selectedIndex].value;
		switch(currentType){
			case 'Ring':
				specificAttributesDiv.innerHTML="Special Attribute:<input type='text' name='Special Attribute'/><br/>";
				break;
			case 'Staff':
				specificAttributesDiv.innerHTML="Spells (One at a time):<input type='text' name='Spells'/><br/>Min Charges:<input type='text' name='minCharges'/><br/>Max Charges:<input type='text' name='maxCharges'/><br/>";
				break;
			case 'Wand':
				specificAttributesDiv.innerHTML="Spell:<input type='text' name='Spell'/><br/>Min Charges:<input type='text' name='minCharges'/><br/>Max Charges:<input type='text' name='maxCharges'/><br/>";
				break;
			case 'Weapon':
				specificAttributesDiv.innerHTML="Min Bonus:<input type='text' name='minBonus'/><br/>Max Bonus:<input type='text' name='maxBonus'/><br/>Special Attributes (One at a time):<input type='text' name='Special Attributes'/><br/>";
				break;
			default:
				specificAttributesDiv.innerHTML='';
		}
	}
</script>

<h1>Search Treasures</h1>
<form method='get' action='search.php'>
Name: <input name='name' type='text' /><br/>
Min Price: <input name='minPrice' type='text' /><br/>
Max Price: <input name='maxPrice' type='text' /><br/>
Type: <select name='type' id='typeSelect' onchange='addTypeSpecificAttributes();'>
			<option value=''>---</option>
			<option value='Ring'>Ring</option>
			<option value='Staff'>Staff</option>
			<option value='Wand'>Wand</option>
			<option value='Weapon'>Weapon</option>
		</select><br/>
<div id='typeSpecificAttributesDiv'>
</div>
<input type='submit' value='Search' />
</form>

<?php

//MongoDB code will go here

include('footer.php');
?>

 

The Search Flow

 

That’s it for the first half of “search.php”. Now for the second, MongoDB focused half.

 

Let’s start by reviewing what we want to happen when visiting the search page. If we don’t have any user search requirements we will just display every treasure in the collection. If we do have search requirements we only want to show treasures that match.

 

Now a quick reminder on how we can use the PHP version of find both to search for items and to just display everything.

 

In order to search a collection you have to pass find an array of key/value pairs.

 

If instead you just want to access every single item in a collection you can either give find zero arguments or you can pass it an empty array.

 

This means that the easiest way to do what we want to do is to create an empty array, fill it with user search requirements and then give it to the database. If there are no user search terms the array will stay empty and we’ll get every item out of the collection, just like we wanted. If there are search requirements then find will only give us matching items, which is also what we want.

 

So let’s it get our MongoDB focused code started like this:

 

$criteria = new array();

//Fill $criteria with search criteria here

$connection = new Mongo();
$cursor = $connection->treasurebag->treasure->find($criteria);

//Print results here

 

Let’s Copy Paste Some Print Code

 

Before we start worrying about the user’s input let’s make sure our base case with no input and a blank array works properly. For this we’re going to grab the treasure table printing code form “index.php” and drop it in near the end of “search.php”, after the database call but before we include the footer.

 

echo '<h2>Search Results</h2>';
echo '<table><tr><td>Name</td><td>Price</td><td>Type</td></tr>';
while($document = $cursor->getNext()){

    $treasureID = $document['_id'];
    $name = $document['Name'];
    $price = $document['Price'];
    $type = $document['Type'];

    echo "<tr><td><a href='viewItem.php?id=$treasureID'>$name</a></td>
                <td>$price</td>
                <td>$type</td></tr>";

}
echo '</table>';

 

If everything is working properly you should be able to refresh “search.php” and see a compelete listing of the treasures in your treasure collection.

 

Checking For Input

 

Now that you know the empty case is working it’s time to start working on what our code should do if the user has actually entered some search criteria. All the rest of the code in this tutorial belongs after declaring the empty $criteria array but before we make our call to the database, so make some space in your code and let’s get started!

 

Between our four different treasure types and all their unique attributes there are a lot of different pieces of data that might or might not be inside of the $_GET array. And for every single one of those pieces of data we’re going to do the same thing.

 

if( !empty( $_GET['ATTRIBUTE NAME'] ) ){
   //Add search term to criteria area
}

 

For example:

 

if(!empty($_GET['name'])){
   //Add name to search criteria
}

 

Using this example go ahead and write the basic if statement for all the other possible attributes. You can figure out what they are from examining the HTML form and form modification script, or you can just use this handy list (case is important): name, minPrice, maxPrice, type, Special_Attribute, minCharges, maxCharges, Spells, Spell, minBonus, maxBonus, Special_Attributes.

 

Searching For Exact Matches With MongoDB and PHP

 

Now that we can figure out which search terms the user has or hasn’t filled out we can finally start building the search criteria array. There are three major types of searches we might run into as part of Treasure Bag and I’m going to give each one their own mini-section.

 

The easiest and most straightforward search is when we are looking for an exact match. The user only wants treasures named “Orc Poker” or the user only wants items of type “Ring”. To search MongoDB for an exact match all you have to do is add the key value pair to the criteria array. Let’s use “name” as an example of how to do this in code:

 

if(!empty($_GET['name']) ){
   $criteria['Name'] = $_GET['name'];
}

 

It’s pretty simple. When we see that the user is asking for a specific name all we do is add a ‘Name’ entry to our array and assign it whatever value the user is looking for. And that’s all you need to know in order to fill out all the other exact match entries: type, Special_Attribute and Spell.

 

Greater Than And Less Than In MongoDB with PHP

 

The second type of search we’ll run into is numeric searches. These are a little more difficult because they include entire ranges or values instead of just a single exact value. For example, the user might be looking for items worth 500 or more.

 

In order to ask MongoDB to do a comparison search we actually have to put an array inside our criteria array. The keys to these inner array will be the names of special MongoDB comparison instructions and the value will be the base number we are comparing against.

 

The special MongoDB comparison instructions and what they mean are:

$gt = greater than

$gte = greater than or equal

$lt = less than

$lte = less than or equal

$ne = not equal

 

Here are a few quick samples to show how this works

//Examples only. Do not put in search.php!

//All documents with an item value greater than 500
$criteria['Price'] = array ( '$gt' => 500 );

//All documents with an item value equal to 10000 or less
$criteria['Price'] = array( '$lte' => 10000 );

//All documents with an item value between 300 and 5000
$criteria['Price'] = array ( '$gt' => 500, '$lt' => 5000);

 

But that’s not the only way to build an array inside an array in PHP. Consider this:

 

//These two pieces of code will both result in the same MongoDB search
$criteria1['Price'] = array( '$gte' => 500 );
$criteria2['Price']['$gte'] = 500;

 

For our code we are going to use the second method. This will make it easy to add a maximum search criteria to an array that already has minimum search criteria.

 

Having trouble understanding how that will work? Maybe this code will help clear things up:

 

if(!empty($_GET['minPrice'])){
   $criteria['Price']['$gte'] =intval($_GET['minPrice'])
}

if(!empty($_GET['maxPrice'])){
   $criteria['Price']['$lte'] = intval($_GET['maxPrice']);
}

 

Now follow this same pattern to fill in the code for minBonus, maxBonus, minCharges and maxCharges.

 

Searching MongoDB When Documents Have Arrays

 

The last kind of search we will run into deals with values that actually have more than one value. For example, Staffs have a “Spells” attribute that can hold multiple items. When we search for a Staff with a specific spell we don’t want to limit ourselves to Staffs that only have that one exact spell. We want to find any Staff that has that spell anywhere in it’s Spells list.

 

MongoDB has lots of different array searching tricks for the different ways you might want to search through arrays inside of documents inside of collections. Finding any array that features a particular item at least once, like we want to do, is actually one of the easiest searches to program. It even uses the exact same syntax as looking for an exact match. Here’s an example using Spells:

 

if(!empty($_GET['Spells'])){
   $criteria['Spells']=$_GET['Spells'];
}

 

Even though this code looks like something we’ve already done it’s important to know to understand that MongoDB will treat it differently . When a keyword only has one value this syntax means “Find an exact match”. But when keyword has an entire array of values this syntax means “Matches any array that has this value no matter what else is in the array”.

 

Now based off this pattern you can fill in the Special_Attributes if statement, which should be your last one.

 

No Results

 

If you’ve been messing around with your new search form you might have noticed that some searches have zero results. When this happens your code will still print the beginning of the treasure list table, it just won’t have anything besides the column names. This is pretty ugly looking. Why not change the code so that an empty result set generates an apologetic warning instead of a mutilated table?

 

In order to generate an empty result warning we’re going to need some way to tell when our results are empty. Forunately, MongoDB has us covered. Remember the cursor class that we’ve been using to cycle through search results? Well that class also has a handy little function called count that lets you know exactly how many results you have to work with. So checking for empty results is as easy as checking whether count is returning zero.

 

if( $cursor->count() == 0 ){
   echo "<h2>No Matching Treasure Found</h2>";
}
else{
   //Inventory table code you already wrote goes here
}

 

And that’s it! You’ve successfully implemented every use case in our design document. Or at least, you should have. It’s time to test whether your code actually works.

 

Testing

 

There are tons of use cases for search. Here are a few to think about:

  • Search by item type. Make sure no items of the wrong type show up. Make sure that all the items of the right type do show up.
  • For minimum and maximum values make sure that items on the edge show up. If the user asks for treasures with a minimum price of 1000 then items worth exactly 1000 should still show up.
  • Create multiple staffs that all share one spell but otherwise have different Spells arrays. Make sure that they all show up when you search for that one spell. Make sure they don’t all show up if you choose a spell that only one staff has.
  • Search for multiple attributes at the same time and make sure only items that fit all requirements show up. If you choose item type “ring” and max price 500 you should have no non-ring or above 500 items.

Screen Shots

Searching all treasure types at once to find item inside a specific price range

Searching all treasure types at once to find item inside a specific price range

The Dark Staff has multiple spells, but because at least one of those is "Darkness" it shows up for this search

The Dark Staff has multiple spells, but because at least one of those is “Darkness” it shows up for this search

Complete Code

Here is what my final “search.php” file looked like:

 

<?php
include('header.php');
?>
<script>
    function addTypeSpecificAttributes(){
        var specificAttributesDiv =  document.getElementById('typeSpecificAttributesDiv');
        var typeSelect = document.getElementById('typeSelect');
        var currentType = typeSelect.options[typeSelect.selectedIndex].value;
        switch(currentType){
            case 'Ring':
                specificAttributesDiv.innerHTML="Special Attribute:<input type='text' name='Special Attribute'/><br/>";
                break;
            case 'Staff':
                specificAttributesDiv.innerHTML="Spells (One at a time):<input type='text' name='Spells'/><br/>Min Charges:<input type='text' name='minCharges'/><br/>Max Charges:<input type='text' name='maxCharges'/><br/>";
                break;
            case 'Wand':
                specificAttributesDiv.innerHTML="Spell:<input type='text' name='Spell'/><br/>Min Charges:<input type='text' name='minCharges'/><br/>Max Charges:<input type='text' name='maxCharges'/><br/>";
                break;
            case 'Weapon':
                specificAttributesDiv.innerHTML="Min Bonus:<input type='text' name='minBonus'/><br/>Max Bonus:<input type='text' name='maxBonus'/><br/>Special Attributes (One at a time):<input type='text' name='Special Attributes'/><br/>";
                break;
            default:
                specificAttributesDiv.innerHTML='';
        }
    }
</script>

<h1>Search Treasures</h1>
<form method='get' action='search.php'>
Name: <input name='name' type='text' /><br/>
Min Price: <input name='minPrice' type='text' /><br/>
Max Price: <input name='maxPrice' type='text' /><br/>
Type: <select name='type' id='typeSelect' onchange='addTypeSpecificAttributes();'>
            <option value=''>---</option>
            <option value='Ring'>Ring</option>
            <option value='Staff'>Staff</option>
            <option value='Wand'>Wand</option>
            <option value='Weapon'>Weapon</option>
        </select><br/>
<div id='typeSpecificAttributesDiv'>
</div>
<input type='submit' value='Search' />
</form>

<?php

$criteria = array();
if(!empty($_GET['name'])){
    $criteria['Name']=$_GET['name'];
}
if(!empty($_GET['minPrice'])){
    $criteria['Price']['$gte'] =intval($_GET['minPrice']);
}
if(!empty($_GET['maxPrice'])){
    $criteria['Price']['$lte'] = intval($_GET['maxPrice']);
}
if(!empty($_GET['type'])){
    $criteria['Type']=$_GET['type'];
}
if(!empty($_GET['Special_Attribute'])){
    $criteria['Special Attribute']=$_GET['Special_Attribute'];
}
if(!empty($_GET['minCharges'])){
    $criteria['Charges']['$gte']=intval($_GET['minCharges']);
}
if(!empty($_GET['maxCharges'])){
    $criteria['Charges']['$lte']=intval($_GET['maxCharges']);
}
if(!empty($_GET['Spells'])){
    $criteria['Spells']=$_GET['Spells'];
}
if(!empty($_GET['Spell'])){
    $criteria['Spell']=$_GET['Spell'];
}
if(!empty($_GET['minBonus'])){
    $criteria['Bonus']['$gte']=intval($_GET['minBonus']);
}
if(!empty($_GET['maxBonus'])){
    $criteria['Bonus']['$lte']=intval($_GET['maxBonus']);
}
if(!empty($_GET['Special_Attributes'])){
    $criteria['Special Attributes']=$_GET['Special_Attributes'];
}

$connection = new Mongo();
$cursor = $connection->treasurebag->treasure->find($criteria);

if($cursor->count()==0){
    echo "<h2>No Matching Treasure Found</h2>";
}
else{
    echo '<h2>Search Results</h2>';
    echo '<table><tr><td>Name</td><td>Price</td><td>Type</td></tr>';
    while($document = $cursor->getNext()){

        $treasureID = $document['_id'];
        $name = $document['Name'];
        $price = $document['Price'];
        $type = $document['Type'];

        echo "<tr><td><a href='viewItem.php?id=$treasureID'>$name</a></td>
                    <td>$price</td>
                    <td>$type</td></tr>";

    }
    echo '</table>';
}

include('footer.php');
?>

 

Why Did We Use MongoDB?

 

Now that we’ve finished up the search interface and you’ve proved to yourself that it works let’s take a moment to appreciate the flexibility of MongoDB. Do a couple searches based on minimum and maximum price. Notice how the results (probably) include a mix of all four different types of items.

 

I’ll let that sink in.

 

This entire project uses only one MongoDB collection, but we were able to keep track of four different kinds of items with it. And because we are only using one collection we can search and sort all of our treasures with only one database call.

 

To do the same thing in MySQL we would probably have to have a different table for every different type of treasure. Creating, sorting or searching a list of all of our treasures would probably require joining multiple tables together.

 

MongoDB isn’t a miracle cure and it has a few weaknesses that make it a poor choice for certain applications. But this program also shows that there are certain things that only MongoDB can do. Next time you find yourself struggling to design a database that can work well with sets of irregular data, remember the flexibility of MongoDB.

 

Conclusion

Congratulations! You’ve successfully completed my intermediate MongoDB tutorial and have proved yourself capable of using PHP and MongoDB. If you feel like you still need more practice why not go back to the start of the tutorial and complete all the BONUS exercises I included at the end of each tutorial.

 

If you’ve already completed all the BONUS exercises, I have nothing left to teach you. Go forth, programmer, and show your MongoDB prowess unto the world!

 

BONUS!

All you character database enthusiasts probably know what’s coming. Build a search form that lets you search your character database based off of character name, class, level or whatever it is you’ve been storing during your exercises.

 

BONUS BONUS!!

This has nothing to do with MongoDB, but wouldn’t it be nice if our search form automatically filled itself with the user’s current search terms instead of resetting itself every time the user hit’s search? Add some PHP to the form so that it can detect $_GET variables and fill itself out accordingly. Nothing too hard here, just tedious.

MongoDB Tutorial Part 8: Deleting Items

Here One Day, Gone The Next

 

Practically every application that lets you add items to a database is also going to need a way to remove them. A dealership just sold a car and needs it removed from their inventory database. An employee quit and needs to be removed from the staff database. Or in our case, a player has sold or lost one of his treasures and wants to remove it from his Treasure Bag.

 

Deleting data is important!

 

Fortunately, this tutorial on removing items from a MongoDB database is going to be really short and simple. If you remember back to tutorial 3 the syntax for finding items and deleting items is almost identical. Which means that if you know how to find a specific item you also know how to delete a specific item. And we already covered finding one specific item back in tutorial 6 with “viewItem.php”.

 

With that in mind, let’s review “viewItem.php” really quickly. Remember the steps we used to find a specific item based off of it’s id?

 

$itemID = $_GET['id'];
$criteria['_id'] = new MongoId($itemID);

$c = new Mongo();

$itemAttributes=$c->treasurebag->treasure->findOne($criteria);

 

delete.php

 

The code for “delete.php” is going to look very similar to the item viewing code we just reviewed. Open your editor, create a file named something like “delete.php” and type in the following code:

 

$itemID = $_GET['id'];
$criteria['_id'] = new MongoId($itemID);

$c = new Mongo();

$c->treasurebag->treasure->remove($criteria);

 

It’s identical to our item viewing code except for that last line. Instead of using findOne, like we did for item viewing, we’re using the remove function. You just give remove a set of key/value pairs and it will remove any items in the collection that match.

 

In our case, we’re passing it a unique match between _id and a specific MongoID, so it should only ever delete one item. But you can also use this function to delete multiple items all at once. For example, you could delete all Weapon type items with a call like:

 

//Deletes all weapons. Do not include in delete.php!!
$newCriteria['type']='Weapon';
$c->treasurebag->treasure->remove($newCriteria);

 

So when writing code that will use remove always double check what information you’re passing it. It’s not fun to accidentally wipe out half a collection when you actually only wanted to remove three items.

 

Finishing Up delete.php

 

Calling remove deletes the item… but now what do we do with the user? Well, if you check back to our design document we decided that after deleting an item the user should be returned to the main index. So at the very end of “delete.php” we should include this line:

 

header('Location:index.php');

 

That’s it! We’re done with delete.php.

 

Getting To Delete.php

 

You can now delete any item by visiting “delete.php?id=mongoID_of_item_to_delete”. But manually finding and typing in MongoIDs would be a nightmare. It would be much better to automatically generate delete URLs for the user.

 

Actually, if you look at the design document we originally planned on having a delete link at the bottom of every item’s detailed view. So let’s open up “itemView.php” and put it in there! All you have to do is go down near the bottom of the code, after the switch statement that prints the item but before the call to include(‘footer.php’). Then add this simple link generator:

 

echo "<br/><a href='delete.php?id=$itemID'>DELETE</a><br/>";

 

This code takes the $itemID we used to generate the detailed item view and creates a new link for deleting that item. Now deleting an item is as simple as finding on the main page, clicking its name for a detailed view and then clicking the delete link at the bottom.

 

Testing

 

Testing this is pretty straightforward. Find or create a treasure that you want to delete. Click on it’s name in the index to see the detailed view. Click on delete and make sure you get automatically returned to the index. Double check the index and make sure the treasure is gone.

 

Complete Code

 

Updated “viewItem.php”

<?php
include('header.php');
$itemID = $_GET['id'];
$criteria['_id'] = new MongoId($itemID);

$c = new Mongo();

$itemAttributes=$c->treasurebag->treasure->findOne($criteria);

echo '<b>Name:</b> '.$itemAttributes['Name'].'<br/>';
echo '<b>Type:</b> '.$itemAttributes['Type'].'<br/>';
echo '<b>Price:</b> '.$itemAttributes['Price'].'<br/>';

switch($itemAttributes['Type']){
    case 'Ring':
        echo '<b>Special Attribute:</b> '.$itemAttributes['Special Attribute'].'<br/>';
        break;
    case 'Weapon':
        echo '<b>Bonus:</b> '.$itemAttributes['Bonus'].'<br/>';
        if( !empty($itemAttributes['Special Attributes']) ){
            echo '<b>Special Attributes:</b>';
            echo '<ul>';
                foreach($itemAttributes['Special Attributes'] as $specialAttribute){
                    echo "<li>$specialAttribute</li>";
                }
            echo '</ul>';
        }
        break;
    case 'Wand':
        echo '<b>Charges:</b> '.$itemAttributes['Charges'].'<br/>';
        echo '<b>Spell:</b> '.$itemAttributes['Spell'].'<br/>';
        break;
    case 'Staff':
        echo '<b>Charges:</b> '.$itemAttributes['Charges'].'<br/>';
        echo '<b>Spells:</b>';
        echo '<ul>';
            foreach($itemAttributes['Spells'] as $spell){
                echo "<li>$spell</li>";
            }
        echo '</ul>';
        break;
}

echo "<br/><a href='delete.php?id=$itemID'>DELETE</a><br/>";

include('footer.php');
?>

“delete.php”

<?php
$itemID = $_GET['id'];
$criteria['_id'] = new MongoId($itemID);

$c = new Mongo();

$c->treasurebag->treasure->remove($criteria);

header('Location:index.php');

?>

Conclusion

 

Treasure Bag is starting to feel like a real piece of software. We can add treasures, delete them, sort them and examine them. The only thing left is to build a useful search tool. So join me next time as we tackle our final challenge.

 

BONUS!

 

If you’ve been diligently doing the bonus challenges you should have a character system that lets you create and view various heroes and villains. Now create a “deleteCharacter.php” script so you can clean out unused characters in the same way you delete unneeded treasures.

MongoDB Tutorial Part 7: User Friendly Data Input

Let’s Be User Friendly

 

Our current Treasure Box web application lets us sort and examine our treasure, but we still have to use the MongoDB command line tool to manually insert new items. There are a lot of obvious problems with managing our database by hand, mostly the fact that it’s just not very user friendly. Non-programmers would be overwhelmed by the idea of typing in MongoDB commands just to add a new treasure and even us programmers tend to make mistakes when we have to type really long insert commands.

 

What we need is a nice friendly user interface. A compact little web form that prompts the user to enter treasure information and then makes sure only good data makes it into the database. Something simple enough a non-programmer can use it and smart enough that we don’t have to worry about what happens if someone has a typo. Something like the treasure creation form we prototyped way back in the design document. Today we’re going to build that.

 

Creating a Treasure Entry Form

 

If you look at our header, we already have a link for “Add Treasure” pointing to a non-existant page called “add.php”. That’s where we want to put our treasure creation form, so create a new “add.php” form and get ready to fill it with code. Our goal for the page is pretty simple. Every treasure has a name, price and type so the page needs an input field for each of those. The treasure type should be a dropdown list and once the user has chosen a specific treasure type we should add input fields for the extra attributes related to that type. So if the user chooses “Wand” from the type dropdown the form should add a “Charges” and “Spell” field.

 

Now this is a MongoDB tutorial, not an HTML or Javascript tutorial, so I’m just going to give you a simple add.php page instead of walking you through it line by line. It’s not the prettiest thing ever, nor is it the best Javascript ever built but it gets the job done and is sufficient for a practice program. Feel free to write your own input form if you need the practice or just can’t stand using anything other than perfect standards-compliant web forms.

 <?php
include('header.php');
?>
<script>
    function addTypeSpecificAttributes(){
        var specificAttributesDiv =  document.getElementById('typeSpecificAttributesDiv');
        var typeSelect = document.getElementById('typeSelect');
        var currentType = typeSelect.options[typeSelect.selectedIndex].value;
        switch(currentType){
            case 'Ring':
                specificAttributesDiv.innerHTML="Special Attribute:<input type='text' name='Special Attribute'/><br/>";
                break;
            case 'Staff':
                specificAttributesDiv.innerHTML="Spells (Comma Seperated):<input type='text' name='Spells'/><br/>Charges:<input type='text' name='Charges'/><br/>";
                break;
            case 'Wand':
                specificAttributesDiv.innerHTML="Spell:<input type='text' name='Spell'/><br/>Charges:<input type='text' name='Charges'/><br/>";
                break;
            case 'Weapon':
                specificAttributesDiv.innerHTML="Bonus:<input type='text' name='Bonus'/><br/>Special Attributes (Optional, Comma Seperated):<input type='text' name='Special Attributes'/><br/>";
                break;
            default:
                specificAttributesDiv.innerHTML='';
        }
    }
</script>

<h1>Add Treasure</h1>
<form method='post' action='processNewTreasure.php'>
Name: <input name='name' type='text' /><br/>
Price: <input name='price' type='text' /><br/>
Type: <select name='type' id='typeSelect' onchange='addTypeSpecificAttributes();'>
            <option value='none'>---</option>
            <option value='Ring'>Ring</option>
            <option value='Staff'>Staff</option>
            <option value='Wand'>Wand</option>
            <option value='Weapon'>Weapon</option>
        </select><br/>
<div id='typeSpecificAttributesDiv'>
</div>
<input type='submit' value='Add Treasure' />
</form>

<?php
include('footer.php');
?>

 

Adding Data To MongoDB With PHP

 

Do you remember how to add data to MongoDB from the command line? If not, go back to tutorial 3. You should see something a lot like this:

 

use treasurebag
db.treasure.insert( { “Name” : ”The Precious”, 
         “Price” : 10000, “Type” : “Ring”, 
         “Special Attribute” : “Invisibility”} )

 

It’s almost the same in PHP:

 

$connection->treasurebag->treasure->insert( array( “Name” => “The Precious”, 
                         “Price” => 10000, “Type” => “Ring”, 
                         “Special Attribute” => “Invisibility” ) );

 

I’m sure you can see the pattern. Choose the right database, choose the right collection and then insert a bunch of key/value pairs. Simple stuff.

 

One important thing to know is that as long as you have an array of key/value pairs it doesn’t matter whether you create the array on the same line as the insert or prepare it earlier. For example, this code will work the exact the same as the PHP sample above:

 

$insertData[“Name”] = “The Precious”;
$insertData[“Price”] = 10000;
$insertData[“Type”] = “Ring”;
$insertData[“Special Attribute”] = “Invisibility”;

$connection->treasurebag->treasure->insert( $insertData );

 

Building the key/value array separately like this can be a useful trick for keeping code clean and flexible.

 

Processing Treasures With processNewTreasure.php

 

If you look closely at the input form for add.php you’ll notice that the form sends it’s data to processNewTreasure.php. That’s the file where we’re going to be doing all of our real work so fire up your favorite code editor and create a blank processNewTreasure.php to work with.

 

Processing user input is a three step process. First, you get the user input. Second, you make sure that the input is clean and complete. If any information is missing or wrong you want to avoid putting it in the database and warn the user that they need to try again. Third, once you’re sure the data is OK, you finally insert it into the database.

 

A professional grade solution would have some heavy duty data and error checking to make sure that all user input was perfect. It would double check that things that are supposed to be numbers are numbers and that strings follow acceptable patterns. It would also have layers of error checking around all database calls to make sure that nothing went wrong while inserting or retrieving data.

 

But we’re only writing practice code, so we’re going to cut a few corners. We will make sure that the user fully filled out the treasure form, but we’re not going to obsess over exactly what they typed in. We will make sure that numbers are numbers… but if they aren’t we’ll just set them to 0 and move on instead of failing and warning the user. And we’re just going to pretend that databases never fail because on a project this small and local they usually don’t.

 

Just remember that if you were building this sort of project for a professional client you would want to kick things up a notch. I don’t want to hear any complaints about people using this sort of code on a production server and then getting in trouble when their application crashes and loses a million dollars worth if information.

 

Printing Errors

 

As I mentioned above, if the user makes an error we want to let them know so they can try again. Printing a simple message is pretty easy. We just

 
include('header.php');
//Error message here
include('footer.php');

 

That’s just three lines to create a nice looking page with our error front and center. But there are tons of places in our code where we might need to print an error message and typing the same three lines over and over again can get boring.

 

Plus, in the future we might change how we want to show errors. Maybe we don’t want to print the entire ‘header.php’ file and instead create a special new page style just for errors. In that case it would be a nightmare to have to track down and modify ever single place we displayed an error.

 

Instead we’re going to start off processNewTreasure.php with a single function that prints an error. It should accept an error message, print a page with that error message and then exit the program to make sure nothing else happens after the error. For example, if the user forgot to give a treasure a name we don’t want to bother trying to insert it into the database. We should stop right there and let the user know.

 

function printAndExit($message){
   include('header.php');
   echo $message;
   include('footer.php');
   exit();
}

 

Now every time we have an error we can rely on one quick function to warn the user and close our code before anything important can break.

 

Verifying Input

 

Every treasure has to have a name, price and type. Making sure that the user included all this information is a logical first step for processNewTreasure.php.

 

We’re going to use the PHP function empty for this task. Empty does two things for us: it checks whether a variable exists and it makes sure it has an actual value. By using this to check POST variables we can make sure that the user put an actual value into every field we care about. We’ll just do a quick check for whether name, price, or type is empty and then print an error message if they are:

 

if( empty($_POST['name']) or empty($_POST['price']) or empty($_POST['type']) ){
   printAndExit('<h1>INVALID INPUT</h1><h2>Missing treasure name, price or type</h2>');
}

 

Pretty easy to follow. If any of the three major variables are empty we print a simple HTML warning and then exit the program.

 

If none of the variables are empty, we can start building the key/value array that we’re going to insert into MongoDB. Notice that as part of creating the array we’re using the PHP function intval to make sure that price is an integer. This function will turn a string number like “123” into an actual number and will turn anything else into 0. So this way even if a user tries to create an item with a non-number price (like Price: “Pinapple”) we still end up with a nice numeric 0.

 

And while we’re at it we might as well set up a MongoDB connection:

 

$inputData['Name'] = $_POST['name'];
$inputData['Price'] = intval($_POST['price']);
$inputData['Type'] = $_POST['type'];

$connection = new Mongo();

 

Type Specific Input

 

After we’ve made sure the user has given us a name, price and type the next step is to figure out what kind of treasure the user is trying to create and double check that they included the right data types for that treasure. Ex: If they are creating a Ring they better have included a Special Attribute value.

 

Just like with itemView.php we’re going to use a switch statement to decide which code to run for which treasure types. And as a bonus, we can use the default case to catch errors where the user is trying to create a treasure with an improper type.

 

switch($_POST['type']){
   case 'Ring':
      //Process Ring
      break;
   case 'Staff':
      //Process Staff
      break;
   case 'Wand':
      //Process Wand
      break;
   case 'Weapon':
      //Process Weapon
      break;
   default:
      printAndExit('<h1>INVALID TREASURE TYPE</h1><h2>UNABLE TO ADD NEW TREASURE TO DATABASE</h2>');
}

 

Processing A Staff

 

So what exactly do we need to put into those case statements to make everything work? Let’s use treasure type Staff as an example. Staff treasures have two extra attributes besides the normal name, price and type: Charges and Spells. Charges is a number and Spells is an array of different magic spell names. So the first thing we need to do is make sure that the user included both of these bits of data.

 

if( empty($_POST['Charges']) or empty($_POST['Spells']) ){
   printAndExit('<h1>INVALID INPUT</h1><h2>Missing staff charges or spells</h2>');
}

 

Just like before, we print an error message if any of the POST variables are empty.

 

Once we know we have the data, the next step is to include it inside the key/value array we started building in the first section of the script. Because “Charges” is a number we will use intval to make sure it winds up as an integer. We will also use explode to take the user’s comma separated list of spells (ex: “healing,raise dead,light”) and expand it into the array that the database is expecting:

 
$inputData['Charges']=intval($_POST['Charges']);
$inputData['Spells']=explode(',',$_POST['Spells']);

 

The $inputData array now has a key/value pair for every Staff attribute: Name, Price, Type, Charges and Spells. All that’s left to do is push the array into the database and let the user know everything went well.

 

$connection->treasurebag->treasure->insert($inputData);
printAndExit('<h1>NEW STAFF ADDED TO TREASURE BAG</h1>');

 

Our complete case statement looks like this:

case 'Staff':
   if( empty($_POST['Charges']) or empty($_POST['Spells']) ){
      printAndExit('<h1>INVALID INPUT</h1><h2>Missing staff charges or spells</h2>');
   }
   $inputData['Charges']=intval($_POST['Charges']);
   $inputData['Spells']=explode(',',$_POST['Spells']);
   $connection->treasurebag->treasure->insert($inputData);
   printAndExit('<h1>NEW STAFF ADDED TO TREASURE BAG</h1>');
   break;

 

Processing a Weapon

 

For out next example, let’s take a look at Weapons. The Weapon type is very similar to the Staff type. Both have a numeric value (Weapons have Bonus and Staffs have Charges) and an array value (Weapons have Special Attributes and Staffs have Spells). But there is one big difference. Every Staff has to have a list of Spells, but Weapon Special Attributes are optional. We shouldn’t throw an error if the user didn’t include Special Attributes and we shouldn’t create a Special Attributes entry in our input array unless we actually have something to put there. So the Weapon case statement looks a little different:

case 'Weapon':
   if( empty($_POST['Bonus']) ){
      printAndExit('<h1>INVALID INPUT</h1><h2>Missing weapon bonus</h2>');
   }
   $inputData['Bonus']=intval($_POST['Bonus']);
   if( !empty($_POST['Special_Attributes']) ){
      $inputData['Special Attributes']=explode(',',$_POST['Special_Attributes']);
   }
   $connection->treasurebag->treasure->insert($inputData);
   printAndExit('<h1>NEW WEAPON ADDED TO TREASURE BAG</h1>');
   break;

 

Processing Rings and Wands

 

You have two examples to look at now, so I’m going to let you write the Ring and Wand case statements on your own. If you need a little extra help I have included a complete copy of my processingNewTreasure.php file down at the bottom of the page. Which shouldn’t be too far away because now that we’ve filled in all four case statements we’re basically done.

 

Testing

 

If everything went well you should be able to click on the “Add Treasure” link in the Treasure Bag menu and be taken to our simple treasure form. The form should properly adjust itself when you choose a treasure type and it should properly process new treasures.

 

To make sure that treasure processing really works try adding at least one new version of every type of treasure. You should also purposely submit some bad data to make sure we really are catching and reporting user input errors. Try to create treasures with no names, wands without spells, weapons without bonuses and so on.

 

Screen Shots

 

The treasure input form. Note how choosing "Staff" in the dropdown has added input fields for Charges and Spells

The treasure input form. Note how choosing “Staff” in the dropdown has added input fields for Charges and Spells

Whoops! The user forgot to fill out some important parts of this form.

Whoops! The user forgot to fill out some important parts of this form.

Submitting an incomplete form results in a warning screen

Submitting an incomplete form results in a warning screen

Complete Code

I already listed the complete code for “add.php” near the start of the tutorial. Here’s the complete code for “processNewTreasure.php”.

<?php

function printAndExit($message){
    include('header.php');
    echo $message;
    include('footer.php');
    exit();
}

if( empty($_POST['name']) or empty($_POST['price']) or empty($_POST['type']) ){
    printAndExit('<h1>INVALID INPUT</h1><h2>Missing treasure name, price or type</h2>');
}

$inputData['Name'] = $_POST['name'];
$inputData['Price'] = intval($_POST['price']);
$inputData['Type'] = $_POST['type'];

$connection = new Mongo();

switch($_POST['type']){
    case 'Ring':
        if( empty($_POST['Special_Attribute']) ){
            printAndExit('<h1>INVALID INPUT</h1><h2>Missing ring special attribute</h2>');
        }
        $inputData['Special Attribute']=$_POST['Special_Attribute'];
        $connection->treasurebag->treasure->insert($inputData);
        printAndExit('<h1>NEW RING ADDED TO TREASURE BAG</h1>');
        break;
    case 'Staff':
        if( empty($_POST['Charges']) or empty($_POST['Spells']) ){
            printAndExit('<h1>INVALID INPUT</h1><h2>Missing staff charges or spells</h2>');
        }
        $inputData['Charges']=intval($_POST['Charges']);
        $inputData['Spells']=explode(',',$_POST['Spells']);
        $connection->treasurebag->treasure->insert($inputData);
        printAndExit('<h1>NEW STAFF ADDED TO TREASURE BAG</h1>');
        break;
    case 'Wand':
        if( empty($_POST['Charges']) or empty($_POST['Spell']) ){
            printAndExit('<h1>INVALID INPUT</h1><h2>Missing wand charges or spell</h2>');
        }
        $inputData['Charges']=intval($_POST['Charges']);
        $inputData['Spell']=$_POST['Spell'];
        $connection->treasurebag->treasure->insert($inputData);
        printAndExit('<h1>NEW WAND ADDED TO TREASURE BAG</h1>');
        break;
    case 'Weapon':
        if( empty($_POST['Bonus']) ){
            printAndExit('<h1>INVALID INPUT</h1><h2>Missing weapon bonus</h2>');
        }
        $inputData['Bonus']=intval($_POST['Bonus']);
        if( !empty($_POST['Special_Attributes']) ){
            $inputData['Special Attributes']=explode(',',$_POST['Special_Attributes']);
        }
        $connection->treasurebag->treasure->insert($inputData);
        printAndExit('<h1>NEW WEAPON ADDED TO TREASURE BAG</h1>');
        break;
    default:
        printAndExit('<h1>INVALID TREASURE TYPE</h1><h2>UNABLE TO ADD NEW TREASURE TO DATABASE</h2>');
}

?>

Conclusion

 

Hopefully everything has worked for you the same way it worked for me and you can add treasures using our friendly form instead of having to rely on long typed out commands. Your Treasure Bag might be starting to feel a little crowded though, so join me next time as we add a handy delete feature to let us clean up our database with a couple clicks.

 

BONUS!

 

Those of you out there who have been creating a character management system to go with the treasure management system know what to expect by now. Create an “Add New Character” form that lets you create new characters directly inside of the web application instead of having to rely on direct MongoDB commands.

 

BONUS BONUS!!

 

Super observant readers might notice that the design document requires that we return to the index after successfully adding a new treasure. Change the code to navigate to index on success instead of printing a message.

MongoDB Tutorial Part 6.5: Fixing itemView.php

I was working on the next part of this tutorial when I noticed a tiny mistake I made in itemView.php. If you look back at the design document, weapon special attributes are optional. But the code that prints out weapon type treasures acts like every treasure is going to have at least one special attribute. Find this code in itemView.php:

 

  case 'Weapon':
      echo '<b>Bonus:</b> '.$itemAttributes['Bonus'].'<br/>';
      echo '<b>Special Attributes:</b>';
      echo '<ul>';
      foreach($itemAttributes['Special Attributes'] as $specialAttribute){
          echo "<li>$specialAttribute</li>";
      }
      echo '</ul>';
      break;

Notice how it just jumps right into the foreach loop of $itemAttributes[‘Special Attributes’]? If a particular weapon doesn’t have any special attributes that information won’t exist and we’ll get a minor error. So let’s fix it by changing it to something more like this:

 

case 'Weapon':
    echo '<b>Bonus:</b> '.$itemAttributes['Bonus'].'<br/>';
    if( !empty($itemAttributes['Special Attributes']) ){
        echo '<b>Special Attributes:</b>';
        echo '<ul>';
            foreach($itemAttributes['Special Attributes'] as $specialAttribute){
                echo "<li>$specialAttribute</li>";
            }
        echo '</ul>';
    }
    break;

 

Now the code will only try to print special attributes when there are special attributes to print and won’t throw errors when it runs into a boring no-attribute weapon.

 

That’s all for this mini-update. Tutorial 7 coming soon!