PHP & MongoDB: Very Simple Add, Edit, Delete, View (CRUD) [Beginner Tutorial]

In this article, I will be presenting simple PHP & MongoDB code to add, edit, delete and view data. This kind of system is also referred to CRUD (Create, Read, Update, Delete).

Here is a step-by-step guide on creating a CRUD system using PHP & MongoDB:

I suppose, you have already installed MongoDB. If not, you may refer to my previous article on Introduction to MongoDB.

Install php-mongodb extension

In Ubuntu Linux, you can install it with the following command:


sudo apt-get install php-mongodb

If you are using PHP 5.6, then you can use the following command:


sudo apt-get install php5.6-mongo

After installing the extension, you have to restart Apache. You can do it with the following command in Ubuntu:


sudo service apache2 restart

We will now create a new MongoDB database. Let us name the database as test. We will also create a new table named users and add some data into that table.

In MongoDB,
Tables are called as “Collection”
Rows are called as “Documents”
Columns are called as “Fields”

Open terminal/command-prompt & Go to Mongo Shell with the following command:


mongo

Show all databases


show dbs

Create new database named test

use command will create & switch to a new database if not present OR it will only switch to the database if already present.


> use test
switched to db test

Create unique index for email field

We make “email” field as unique so that duplicate entries for emails will generate error message. Each user is uniquely identified by “email”. The user ID in MongoDB is automatically generated as 12-byte ObjectId.


db.users.createIndex({"email":1}, {unique:true})

Create collection named users

Collection in MongoDB is equivalent to tables in MySQL or other RDBMS.


> db.users.insert({name:"Mukesh Chapagain", age:88, email:"mukesh@example.com"})
> db.users.insert({name:"Raju Sharma", age:77, email:"raju@example.com"})
> db.users.insert({name:"Krishna Yadav", age:65, email:"krishna@example.com"})

Query the collection


> db.users.find().pretty()
{
    "_id" : ObjectId("5946517675f3fc671900a6c1"),
    "name" : "Mukesh Chapagain",
    "age" : 88,
    "email" : "mukesh@example.com"
}
{
    "_id" : ObjectId("5946517f75f3fc671900a6c2"),
    "name" : "Raju Sharma",
    "age" : 77,
    "email" : "raju@example.com"
}
{
    "_id" : ObjectId("5946518375f3fc671900a6c3"),
    "name" : "Krishna Yadav",
    "age" : 65,
    "email" : "krishna@example.com"
}

Now, we will create a config.php file which contains database connection code. This code connects to the MongoDB database. This file is included in all PHP pages where database connection is necessary.

config.php


<?php
/**
 * Connection to MongoDB
 * 
 * $connection = new MongoClient(); // connects to localhost:27017
 * 
 * For remote host connection
 * 
 * $connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
 * $connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port
 * 
 * Connection using database username and password
 * 
 * $connectionUrl = sprintf('mongodb://%s:%d/%s', $host, $port, $database);
 * $connection = new Mongo($connectionUrl, array('username' => $username, 'password' => $password));
 */ 
$connection = new MongoClient();

/**
 * Select database named "test"
 */ 
$db = $connection->test;
?>

To add data into database, we need an html form.

add.html


<html>
<head>
    <title>Add Data</title>
</head>

<body>
    <a href="index.php">Home</a>
    <br/><br/>

    <form action="add.php" method="post" name="form1">
        <table width="25%" border="0">
            <tr> 
                <td>Name</td>
                <td><input type="text" name="name"></td>
            </tr>
            <tr> 
                <td>Age</td>
                <td><input type="text" name="age"></td>
            </tr>
            <tr> 
                <td>Email</td>
                <td><input type="text" name="email"></td>
            </tr>
            <tr> 
                <td></td>
                <td><input type="submit" name="Submit" value="Add"></td>
            </tr>
        </table>
    </form>
</body>
</html>

Form action on add.html is add.php. It means that the submitted form data will go to add.php. In add.php, we do a simple validation of checking if the entered name, email & age are empty or not. If they are all filled then the data will be inserted into database table/collection.

add.php


<html>
<head>
    <title>Add Data</title>
</head>

<body>
<?php
//including the database connection file
include_once("config.php");

if(isset($_POST['Submit'])) {   
    $user = array (
                'name' => $_POST['name'],
                'age' => $_POST['age'],
                'email' => $_POST['email']
            );
        
    // checking empty fields
    $errorMessage = '';
    foreach ($user as $key => $value) {
        if (empty($value)) {
            $errorMessage .= $key . ' field is empty<br />';
        }
    }
    
    if ($errorMessage) {
        // print error message & link to the previous page
        echo '<span style="color:red">'.$errorMessage.'</span>';
        echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";  
    } else {
        //insert data to database table/collection named 'users'
        $db->users->insert($user);
        
        //display success message
        echo "<font color='green'>Data added successfully.";
        echo "<br/><a href='index.php'>View Result</a>";
    }
}
?>
</body>
</html>

Data from database is fetched and displayed in index.php file. This is our homepage. This file also contains a link to add data. On every row of displayed data, there is also a link to edit and delete data. Below is a sample image of our homepage:

crud php

index.php


<?php
//including the database connection file
include_once("config.php");

// select data in descending order from table/collection "users"
$result = $db->users->find()->sort(array('_id' => -1));
?>

<html>
<head>  
    <title>Homepage</title>
</head>

<body>
<a href="add.html">Add New Data</a><br/><br/>

    <table width='80%' border=0>

    <tr bgcolor='#CCCCCC'>
        <td>Name</td>
        <td>Age</td>
        <td>Email</td>
        <td>Update</td>
    </tr>
    <?php   
    foreach ($result as $res) {
        echo "<tr>";
        echo "<td>".$res['name']."</td>";
        echo "<td>".$res['age']."</td>";
        echo "<td>".$res['email']."</td>";  
        echo "<td><a href=\"edit.php?id=$res[_id]\">Edit</a> | <a href=\"delete.php?id=$res[_id]\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";     
    }
    ?>
    </table>
</body>
</html>

Each row/document of data can be edited separately. Row/Document ID is passed in the URL of edit.php. ID uniquely identifies the data entry.

While adding data, we had two files: add.html and add.php. While editing data, I have kept the entire thing in a single edit.php file. Edit form in HTML and database update code in PHP are present in the same file.

In the code below, at first a single row entry of data is fetched based on the id. The fetched data is displayed in the edit form. When user edits the data and submits the form, then some simple validation is done for empty data. When everything is correct, then that particular entry of data is updated in database.

edit.php


<?php
// including the database connection file
include_once("config.php");

if(isset($_POST['update']))
{   
    $id = $_POST['id'];
    $user = array (
                'name' => $_POST['name'],
                'age' => $_POST['age'],
                'email' => $_POST['email']
            );
    
    // checking empty fields
    $errorMessage = '';
    foreach ($user as $key => $value) {
        if (empty($value)) {
            $errorMessage .= $key . ' field is empty<br />';
        }
    }
            
    if ($errorMessage) {
        // print error message & link to the previous page
        echo '<span style="color:red">'.$errorMessage.'</span>';
        echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";  
    } else {
        //updating the 'users' table/collection
        $db->users->update(
                        array('_id' => new MongoId($id)),
                        array('$set' => $user)
                    );
        
        //redirectig to the display page. In our case, it is index.php
        header("Location: index.php");
    }
} // end if $_POST
?>
<?php
//getting id from url
$id = $_GET['id'];

//selecting data associated with this particular id
$result = $db->users->findOne(array('_id' => new MongoId($id)));

$name = $result['name'];
$age = $result['age'];
$email = $result['email'];
?>
<html>
<head>  
    <title>Edit Data</title>
</head>

<body>
    <a href="index.php">Home</a>
    <br/><br/>
    
    <form name="form1" method="post" action="edit.php">
        <table border="0">
            <tr> 
                <td>Name</td>
                <td><input type="text" name="name" value="<?php echo $name;?>"></td>
            </tr>
            <tr> 
                <td>Age</td>
                <td><input type="text" name="age" value="<?php echo $age;?>"></td>
            </tr>
            <tr> 
                <td>Email</td>
                <td><input type="text" name="email" value="<?php echo $email;?>"></td>
            </tr>
            <tr>
                <td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
                <td><input type="submit" name="update" value="Update"></td>
            </tr>
        </table>
    </form>
</body>
</html>

Each row/document of data can be deleted separately. Row/Document ID is passed in the URL of delete.php. ID uniquely identifies the data entry. After deletion, the user is redirected to homepage (index.php).

delete.php


<?php
//including the database connection file
include("config.php");

//getting id of the data from url
$id = $_GET['id'];

//deleting the row from table/collection
$db->users->remove(array('_id' => new MongoId($id)));

//redirecting to the display page (index.php in our case)
header("Location:index.php");
?>

Download Full Source Code: Simple Create, Read, Update, Delete in PHP & MongoDB

Hope this helps. Thanks.