How to create a simple CRUD application using Mongo db and php

In this tutorial I’m going to show you how to create a simple crud application using Mongo DB and php. If you want to know how to install Mongo DB, visit the link below:

How to install Mongo DB on php

Configuration File
First you’re going to need to create a database configuration file which connects to your Mongo DB. Just like in MySQL, we also make use of a configuration file that we will just include on the files where we are going to need to query the database. This is to save time and avoid repeating of code.

<?php
$conn = new Mongo();
$db = $conn->test;
$collection = $db->people;
?>

Let me break down the code for you:

  • $conn = new Mongo()  – this initializes the Mongo DB class which contains all the methods which you can use to manipulate data in mongo DB through php.
  • $db = $conn->test – the default name for the Mongo database is test. This code is used for connecting to the database.
  • $collection = $db->people – collections are similar to tables in mysql. This code is used to reference the collection called people. But not unlike in mysql where you have to create the table first from the mysql console or a third-party database manager like phpmyadmin or heidi sql.
    In mongo DB you can basically use any collection name that you want, without having to create it.

 

Create
Now on to the exciting part, first let’s try inserting data into the database. Go ahead and create a form which the user can interact with. Don’t forget to include the database configuration file.

<?php
require_once('mongo_config.php');
?>
<form action="create_users.php" method="post">
<p>
<label for="name">Name:</label>
<input type="text" name="name">
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age">
</p>
<p>
<label for="likes">Likes:</label>
<input type="text" name="likes">
</p>
<p>
<input type="submit" value="Save">
</p>
</form>

Next, create the function that will check if all the values has been filled out. What the function does is to loop through the array of values that is being passed through it. But we have check first if the value is actually an array so that we don’t get any errors. If one or more values are empty, the function returns 1. If not then it returns its original value which is 0. We can then use that returned value to make a decision whether to continue the insertion of the record or not.

<?php
function check_empty($ar){
    $empty = 0;
    if(is_array($ar)){
        foreach($ar as $v){
            if(empty($v)){
              $empty = 1;
            }
        }
    }
return $empty;
}	
?>

Next is the code for inserting records.

<?php
if(!empty($_POST)){
	$people = $collection->find();
	$people_count = $people->count();
	
	$empty = check_empty($_POST);
	if($empty != 1){
		$id = $people_count + 1;
		$name = $_POST['name'];
		$age = $_POST['age'];
		$likes = $_POST['likes'];
		
		$person = array('id'=>$id, 'name'=>$name, 'age'=>$age, 'likes'=>$likes);
		
		$collection->insert($person);
		echo $name . ' is registered!';
	}else{
		echo 'Please fill out all the fields!';
	}
}
?>

  • if(!empty($_POST)) – First we checked if the $_POST superglobal is empty. This is the first step, because we don’t want to be executing all the code when the user access the page.
  • $people = $collection->find() – Call the find() method, this returns an array of all the records in the collection. Which if you still remember, the people collection as we have declared in the configuration file.
  • $people_count = $people->count() – Call the count() method, as the names suggests it just counts how many records are in the people collection. We then store that value into the $people_count variable.
  • $empty = check_empty($_POST) – Call the check_empty() function that we created earlier, and use the $_POST superglobal as an argument.

Next is just the assigning of the values from the submitted form to a php variable. Then place all those values in an aarray called $person. We then use the insert() function and supply the $person array as an argument. Nice and simple.

 

Read
Fetching the data is also dead simple. We only have to call the find() method and loop through it. Of course, we also need to use the count() method to check if there are actually records to fetch. We ditch the whole thing if the $people_count stores the value of 0.

<?php
require_once('mongo_config.php');


$people = $collection->find();
$people_count = $people->count();

echo $people_count . ' records found<br/>';

if($people_count > 0){
?>

<table border="1">
<thead>
	<tr>
		<th>ID</th>
		<th>Name</th>
		<th>Age</th>
		<th>Likes</th>
	</tr>
</thead>
<tbody>
	<?php foreach($people as $v){ ?>
	<tr>
		<td><a href="update_user.php?name=<?php echo $v['name']; ?>"><?php echo $v['id']; ?></a></td>
		<td><?php echo $v['name']; ?></td>
		<td><?php echo $v['age']; ?></td>
		<td><?php echo $v['likes']; ?></td>
	</tr>
	<?php } ?>
</tbody>
</table>
<?php } ?>

 

Update
Updating is also dead simple. We just make use of the findOne() function to fetch a single record from the collection. The argument that it will need is an array which contains the field name and its value. We already supplied the value in the link for updating. Were going to make use of the name as the query string(since the id that I supplied doesn’t work for me, grr. I guess the problem is the name id itself, you’ll have to use a different name if you want to make use of a custom id to reference the records).

<a href="update_user.php?name=<?php echo $v['name']; ?>">

Here’s the code(sorry for the poor indentation):

<?php
require_once('mongo_config.php');

if(!empty($_GET['name'])){
$name = $_GET['name'];
$query = array('name'=>$name);

$person = $collection->findOne($query);
$name = $person['name'];
$age =  $person['age'];
$likes =  $person['likes'];

?>
<form action="update_user.php" method="post">
<p>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>" readonly>
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age" value="<?php echo $age; ?>">
</p>
<p>
<label for="likes">Likes:</label>
<input type="text" name="likes" value="<?php echo $likes; ?>">
</p>
<p>
<input type="submit" value="Update">
</p>
</form>
<?php } ?>

Remember that $_GET is not a secure way of passing variables from one page to another. This is just for examples, don’t use it on any project(although personal projects may do, or any projects that will not be used by other people).

To update the record. First we check if any fields is empty, we don’t actually do a thing if one of the fields are empty. Assign the $_POST values to a variable. Call the findOne() method, using the name as the query string. Assign the new values, then commit to the database using the save() function.

<?php 
if(!empty($_POST)){
	$empty = check_empty($_POST);
	if($empty != 1){
	
	$name = $_POST['name'];
	$age = $_POST['age'];
	$likes = $_POST['likes'];
	
	$query = array('name'=>$name);
	$person = $collection->findOne($query);
	
	$person['age'] = $age;
	$person['likes'] = $likes;
	$collection->save($person);
	
	echo 'Update Successful!';
	}
}
?>

Note: we used the check_empty() function again. You might want to copy it on the file if you don’t want to get WHAT FUNCTION ARE YOU TALKING ABOUT errors.

 

Conclusion
That’s it for this tutorial. We have just touch the surface of using Mongo DB and php to create database oriented applications.
Yes I’ve said CRUD application, but I’m going to leave record deletion as your assignment. You just have to make use of the findOne() and the remove() function. Thanks for reading!

7 thoughts on “How to create a simple CRUD application using Mongo db and php

  1. tut is too good, but m facing problems regarding the names of these files, and what are the contents dat have to be grouped together and put into a particular file. help!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s