php mongodb tutorial – find, insert, update and delete records

php mongodb tutorial

Mongodb is very popular open source, document based NoSQL database. In a previous NodeJS mongodb tutorial we explored how to perform CRUD operations on mongdb  database using nodejs. In this php mongodb tutorial you will learn how to fetch, insert, edit, delete records in a mongodb collection  using php.

In this article following tasks are done:

1. Create a database in mongoDB

2. Create a mongodb collection

3. Insert data into mongodb collection

4. Display records in a page from mongodb using php

5. Insert, update, delete records from mongodb database using php

Create database in mongodb

To create a database in mongodb, “use database_name” command is used, if database does not already exist, a new database is created.

> use onlinestore
switched to db onlinestore

View all databases

To view all databases in mongodb, type > show dbs.

> show dbs
local        0.000GB
onlinestore  0.000GB

View current database name

To view current database.

> db
onlinestore

Create a mongodb collection

db.createCollection(collectionName) is used to create a collection.

> db.createCollection("products")
{ "ok" : 1 }

Insert records to mongodb collection

In order to insert records to mongodb collection insert method is used. To insert bulk records,  all records are added in an array.

db.products.insert([{ "_id" : ObjectId("5899b8369ba2868af6d141d5"), "product_name" : "Apple IPhone 6", "price" : "$630", "category" : "Mobile Phone" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141d6"), "product_name" : "Sony Vio", "price" : "$1200", "category" : "Laptop" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141d7"), "product_name" : "Samsung T.V", "price" : "$900", "category" : "Electronics" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141d8"), "product_name" : "Apple IPAD", "price" : "$400", "category" : "Tablet" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141d9"), "product_name" : "MacBook Pro", "price" : "$800", "category" : "Laptop" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141da"), "product_name" : "Dell Laptop", "price" : "$620", "category" : "Laptop" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141db"), "product_name" : "Canon EOS 700D DSLR Camera", "price" : "$400", "category" : "Camera" }, 

... { "_id" : ObjectId("5899b8369ba2868af6d141dc"), "product_name" : "Nikon D7100 DSLR Camera ", "price" : "$440", "category" : "Camera" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141de"), "product_name" : "HTC Phone", "price" : "$200", "category" : "Mobile Phone" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141df"), "product_name" : "LG Monitor", "price" : "$500", "category" : "Electronics" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141e0"), "product_name" : "Samsung Printer", "price" : "$320", "category" : "Electronics" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141e1"), "product_name" : "Samsung Gear Live Black - Made for Android", "price" : "$250", "category" : "Watch" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141e2"), "product_name" : "Apple Watch", "price" : "$380", "category" : "Watch" } ])

BulkWriteResult({
  "writeErrors" : [ ],
  "writeConcernErrors" : [ ],
  "nInserted" : 13,
  "nUpserted" : 0,
  "nMatched" : 0,
  "nModified" : 0,
  "nRemoved" : 0,
  "upserted" : [ ]
})
> 

mongodb find method to fetch records

find() method fetches records from mongodb collection.

db.products.find()

php mongodb extension to access database

Install php mongodb driver

To work with mongodb in php you have to install php mongodb extension. Visit php mongodb packages site and download mongodb driver package compatible with your php version and OS. Unzip and paste php_mongo.dll file inside your WAMP or XAMPP php installation extension folder. Suppose you have installed XAMPP, Then go to php folder and open  ext folder like C:\xampp\php\ext.

Enable mongodb extension in php.ini

Open php.ini file and enable php_mongodb extension.

extension = php_mongodb.dll

After installation of mongodb driver, restart Apache web server. In  root folder if you create a php file and call phpinfo() function you can see mongodb extension is loaded.

php mongodb - php.ini enable mongodb

php mongodb database connection

After mongodb is installed now inside www or public_html folder of your WAMP, XAMPP or LAMP create a directory phpmongo. Create a file config.php. Add the code below to the config file

<?php

$manager     =   new MongoDB\Driver\Manager("mongodb://localhost:27017");

/* success, error messages to be displayed */

 $messages = array(
  1=>'Record deleted successfully',
  2=>'Error occurred. Please try again', 
  3=>'Record saved successfully',
  4=>'Record updated successfully', 
  5=>'All fields are required' );

To connect to a mongodb database mongodb driver manager is used. All database connections are maintained by mongodb driver manager. Database connection is not created on  instantiation of a mongodb driver manager object.

Driver manager takes parameter server address localhost  with  a port 27017. A messages array is created to save  success or error messages to be used later.

PHP mongodb select and display records

Create a file index.php. This page displays records from a mongodb collection.

<?php

require_once('config.php');

$flag    = isset($_GET['flag'])?intval($_GET['flag']):0;

$message ='';

if($flag){

  $message = $messages[$flag];

}

$filter = [];

$options = [
    'sort' => ['_id' => -1],
];

$query = new MongoDB\Driver\Query($filter, $options);

$cursor = $manager->executeQuery('onlinestore.products', $query);

?>
config.php is included into index.php to use mongoDB driver  manager object. When ever a new record is inserted, updated or deleted, user is redirected back to index page with a flag as query string parameter. Based on flag parameter a message from messages array in config is displayed to user.

Next $filter variable is created. Filter can contain any condition to be met to select a records. For example it can be set to select the documents where price is greater than $50. If you are familiar with relational databases then you can consider it as a where clause.

$options array contain additional options such as sorting. mongodb driver’s Query method is used to construct a query and accepts filter and options parameters.

executeQuery method is used to execute a query. Database collection name and a query object is passed to this function and on success a mongodb driver returns a cursor or an exception is thrown otherwise.

php mongodb tutorial - view records

Display all records in a loop

To display all the records to user a table is created with table cell headers #, product name, price, category and action. Using foreach loop all records are displayed from $cursor array.

With product name, price and category, Edit and Delete links are also displayed. Edit link is assigned a class .editclass. This class is used to fire a click event and sends an AJAX request to server when any edit link is clicked. A data-id attribute is added inside edit link and _id value is assigned o it.

Delete link redirects a user to record_delete.php page. A confirmation message is added that confirms record deletion from user.

<table class='table table-bordered'>
   <thead>

      <tr>
            <th>#</th>

            <th>Prodcut</th>

            <th>Price</th>

             <th>Category</th>
    
            <th>Action</th>

      </tr>
  
   </thead>

    <?php 

    $i =1; 

    foreach ($cursor as $document) {   ?>

      <tr>

      <td><?php echo $i; ?></td>

      <td><?php echo $document->product_name;  ?></td>

      <td><?php echo $document->price;  ?></td>        
    
     <td><?php echo $document->category;  ?></td>
      
     <td><a class='editlink' data-id=<?php echo $document->_id; ?> 
             href='javascript:void(0)'>Edit</a> |
        <a onClick ='return confirm("Do you want to remove this
                     record?");' 
        href='record_delete.php?id=<?php echo $document->_id;  ?>'>Delete</td>

      </tr>

     <?php $i++;  

  } 

  ?>

</table>

PHP mongoDB Insert record

To add new documents into a mongodb collection first a form is created inside index.php. Then product_name, category and price fields are defined. A hidden field id is also added. In case of update of a record it contains id of existing record. Form data is posted to record_add.php page.

<form id="form1" name='form1' action="record_add.php" method="post">

         <input type='hidden' name='id' id='id' value="" />

          <table>

          <tr>

            <td><input type='text' name='product_name' id='product_name' placeholder="Product Name" /></td>

            <td><input type='text' name='price' id='price' placeholder="Price" /></td>

           <td><input type='text' name='category' id='category' placeholder="Category" /></td>

          <td><input class='btn' type='submit' name='btn' id='btn' value="Add Records" /></td>

           </tr>

        </table>

    </form>

Create a php page record_add.php. This page includes config.php page to access to mongodb driver manager object to make a connection to mongodb and insert a document to collection. Inside if condition we get product_name, price and category from $_POST super global array. If any of values not entered  error code 5 is sent back to user.

Write operations are added to MongoDB\Driver\BulkWrite and are sent to the server. After adding insert, update or delete operations to bulkwrite operations can be executed.

MongoDB\Driver\WriteConcern is used for describing level of acknowledgement requested from MongoDB. Write operations are executed by executeBulkWrite. It accepts collection name, bulkwrite object and writeconcern.

<?php

  require_once('config.php');

  $product_name = '';

  $price           = 0;

  $category     = '';

  $flag             = 0;
  
  if(isset($_POST['btn'])){

      $product_name  = $_POST['product_name'];
      $price                 = $_POST['price'];
      $category          = $_POST['category'];

      if(!$product_name || !$price || !$category){
  
        $flag = 5;

      }else{
         
           $insRec       = new MongoDB\Driver\BulkWrite;

           $insRec->insert(['product_name' =>$product_name, 'price'=>$price, 'category'=>$category]);
          
           $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
         
             $result       = $manager->executeBulkWrite('onlinestore.products', $insRec, $writeConcern);

          if($result->getInsertedCount()){

            $flag = 3;

          }else{

            $flag = 2;

          }
      }
  }

  header("Location: index.php?flag=$flag");

  exit;

php mongodb tutorial - insert new reocrd

PHP mongodb update record

Fetch existing record form database

To update a record user clicks on Edit link an AJAX GET request is sent to server and server responds with data of clicked document. To send an AJAX request in JADE template engine you can use code below.

First jQuery library is included from jQuery CDN and then inside jQuery ready function an event for the edit links class .editlink is created. Whenever an edit link is clicked this event is executed. $(this).data(‘id’) .val() gets the _id value from data-id attribute of currently clicked link. Using jQuery’s $.ajax method a request is sent to fetchdata.php.

script(src='https://code.jquery.com/jquery-3.1.1.min.js')
 script.
      $(function() {

        $('.editlink').on('click', function(){

          var id = $(this).data('id');

          $.ajax({

            method: "GET",

            url: "fetchdata.php",

            data: { id:  id },

          }).done(function( data ) {

            $('#id').val(data[0]['_id']);

            $('#product_name').val(data[0]['product_name']);

            $('#price').val(data[0]['price']);

            $('#category').val(data[0]['category']);

            $("#subbtn").val('Edit Product');

            $('#form1').attr('action', '/edit');

          });

        });

      });
fetchdata.php page responses with data from mongodb server and value of _id, product_name, price and category is assigned to respective fields in the form.

Value of Add Record button is changed to ‘Edit Records’ and action attribute of form is changed to record_edit.php. Now when user clicks on Edit Records button, data is posted to record_edit.php.

Fetch data from database for a single document

Create a page fetchdata.php and add following code to get data from database server.

<?php

require_once('dbconn.php');

$id    = $_GET['id'];

$result = array();

if($id){

  $filter = ['_id' => new MongoDB\BSON\ObjectID($id)];

  $options = [];

  $query = new MongoDB\Driver\Query($filter,$options);

  $cursor = $manager->executeQuery('onlinestore.products', $query);

  foreach($cursor as $row){

    $result ['product_name'] = $row->product_name;

    $result ['price']        = $row->price;

    $result ['category']     = $row->category;

    $result ['id']           = $id;

  }

  echo json_encode($result);

}

After id parameter is received a filter is created and is converted to mongodb object id. A query is created by passing $filter and $options array. Collection name and $query is passed to executeQuery method and it returns mongodb cursor that contains the records.

Next from cursor data is assigned to array. After encoding data to JSON it is sent back to client side.

php mongodb tutorial - fetch sigle record using ajax

Now create a page record_edit.php and add code below into it. User modifies data in the form and clicks ‘Update Records‘ button, server receives request and data is assigned to variables from $_POST array.

<?php

  require_once('config.php');

  $product_name = '';

  $price        = 0;

  $category  = '';

  $flag          = 0;

  if(isset($_POST['btn'])){

      $product_name = $_POST['product_name'];

      $price        = $_POST['price'];

      $category     = $_POST['category'];

      $id           = $_POST['id'];

      if(!$product_name || !$price || !$category || !$id){

        $flag = 5;

      }else{

          $insRec       = new MongoDB\Driver\BulkWrite;

          
$insRec->update(['_id'=>new MongoDB\BSON\ObjectID($id)],['$set' =>['product_name' =>$product_name, 'price'=>$price, 'category'=>$category]], ['multi' => false, 'upsert' => false]);

          
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);

         
 $result       = $manager->executeBulkWrite('onlinestore.products', $insRec, $writeConcern);

          if($result->getModifiedCount()){

            $flag = 3;

          }else{

            $flag = 2;

          }

      }

  }

  header("Location: index.php?flag=$flag");

  exit;

php mongodb tutorial - update records

Update records into database collection

If user enters all the data correctly then inside else clause a mongodb driver bulkwrite object is created and update command is added to it. bulkwrite object’s update method accepts id and edited data. Here multi =>false means that we are only updating one record.

To update all documents that matches a certain criteria multi parameter is set to true. Upsert parameter if set to true creates a new document if criteria is not met. In this case it is set to false, so it does not create a new document.

writeconcern object is created next. After write concern executeBulkWrite function executes update query. Collection name, bulkwrite object and write concern parameters are passed. Result’s getModifiedCount method contains number of rows effected. On successful execution user is redirected to index.php page with appropriate flag.

PHP mongodb delete records

When a user clicks on Delete link of a record. a confirmation message is displayed. If ok button is clicked,  user is redirected to delete record page.

php mongodb tutorial - record delete confirmation

Create a page record_delete.php and add following code into it.

<?php

  require_once('dbconn.php');

  $id   = $_GET['id'];

  $flag = 0;

  if($id){

    $delRec = new MongoDB\Driver\BulkWrite;

    $delRec->delete(['_id' =>new MongoDB\BSON\ObjectID($id)], ['limit' => 1]);

    $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);

    $result       = $manager->executeBulkWrite('onlinestore.products', $delRec, $writeConcern);

    if($result->getDeletedCount()){

      $flag = 1;

    }else{

      $flag = 2;

    }

    header("Location: index.php?flag=$flag");

    exit;

  }

record_delete.php page gets id from URL query string and creates a bulkWrite object. Next a delete operation is added to bulkwrite object where id of record is passed and limit is set to 1.

After creating writeconcern object, executeBulkWrite method runs query and takes collection name, bulkwrite object and writeconcern parameters. After record is deleted user is redirected to index.php page.

php mongodb tutorial - delete record

Summary

To summarize, this tutorial explores how to perform CRUD operations on a mongodb collection using PHP. Find the php code and mongodb queries in this download link. Follow us on Twitter to keep updated on latest tutorials and articles.

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

About Jason William