How to Perform CRUD in MongoDB Document using PHP Part 1

Introduction

The concept of CRUD (Create, Read, Update, Delete) is to equip developers with the necessary code to create APIs (a set of functions) that run applications, or a service. CRUD is the basis for that. You can do that with MongoDB. Let’s begin by creating and inserting documents using PHP MongoDB. Then we’ll edit and delete a document. This step-by-step tutorial explains exactly how to perform CRUD in MongoDB.

Use PHP to Create a MongoDB Document

Prerequisites

  • MongoDB – Install Mongo DB if you haven’t yet.

  • MongoDB PHP Driver – Install the appropriate PHP driver for your MongoDB version.

  • Verify that the driver is installed and working properly.

pecl search mongo
  • It should look similar to this.
.Matched packages, channel pecl.php.net:
=======================================
Package Stable/(Latest) Local
mongo 1.6.16 (stable) MongoDB database driver
mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • Next, use the command below to verify the PHP version you have installed.
php --version
  • You should see something like this.
PHP 7.2.15-0ubuntu0.18.04.2 (cli) (built: Mar 22 2019 17:05:14) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.15-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

Various MongoDB Drivers and Version Compatibilities

  • Here are some recommendations for different MongoDB versions and their compatible drivers.
PHP DriverMongoDB 4.0MongoDB 3.6MongoDB 3.4MongoDB 3.2MongoDB 3.0MongoDB 2.6
PHPLIB 1.4 + Mongodb-1.6
PHPLIB 1.3 + mongodb-1.4
PHPLIB 1.2 + mongodb-1.3
PHPLIB 1.1 + mongodb-1.2
PHPLIB 1.0 + mongodb-1.1
mongodb-1.0
  • Below, learn about the versions of MongoDB PHP and associated drivers.

PHP Driver and MongoDB Compatibilty Reference

  • This table shows the recommended version(s) of the MongoDB PHP driver for use with a specific version of PHP.
PHP DriverPHP 5.4PHP 5.5PHP 5.6PHP 7.0PHP 7.1PHP 7.2PHP 7.3
mongoDB1.5
mongoDB1.4
mongoDB1.3
mongoDB1.2
mongoDB1.1
mongoDB1.0

How to start MongoDB as a Daemon

  • Press CTRL + ALT + T to open a terminal window.

  • Next, run MongoDB. Since you have permissions, you should be able to use the command sudo.

sudo systemctl start mongod
sudo systemctl status mongod
  • This is what it should look like or something similar to it.
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
Active: active (running) since Mon 2019-04-22 19:27:02 PST; 8min ago
Docs: https://docs.mongodb.org/manual
Main PID: 6598 (mongod)
CGroup: /system.slice/mongod.service
└─6598 /usr/bin/mongod --config /etc/mongod.conf

Apr 22 19:27:02 teamsolo systemd[1]: Started MongoDB Database Server.
lines 1-9/9 (END)

Determine the Project Directory Structure and Associated Files

In order to access files including assets files, you’ll need to specify the project directory structure.

Project Structure and Files
– Private (dir)
— Shared (dir)
— staff_footer.php
— staff_header.php
— database.php
— functions.php
— initialize.php
— query_functions.php
– Public (dir)
— images (dir)
— staff (dir)
— subjects (dir)
— index.php
— new.php
— edit.php
— show.php
— delete.php

The Configuration Files Were Included

NOTE: All the required configuration files are ready. The only thing you need to do in reference to loading it.

Load the application using the initialize.php

  • Access the application by loading the configuration files.
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Assigning file path to PHP constants
//__FILE__ returns the current path to the file
//dirname() returns the path to the parent directory

define("PRIVATE_PATH", dirname(__FILE__));
define("PROJECT_PATH", dirname(PRIVATE_PATH));
define("PUBLIC_PATH", PROJECT_PATH . '/public');
define("SHARED_PATH", PRIVATE_PATH . '/shared');
define("VENDOR_PATH", PROJECT_PATH . '/vendor');

//Assign the root URL to PHP constant
// * Do not need to include the domain
// * Use same document root as webserver
// * Can set a hardcoded value:
// define("WWW_ROOT")
// define ("WWW_ROO" , '');
// * Can dynamically find everything in URL up to "/public"
$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 7;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);

require_once('functions.php'); // all files and browsing related functions goes here
require_once('query_functions.php'); // all database query related functions goes here

The database configuration: database.php

  • MongoDB has a database configuration and it’s database.php. Let’s load it.
// MongoDB\Driver\Manager
$db = new MongoDB\Driver\Manager("mongodb://localhost:27017");

// PHP Library
require_once(VENDOR_PATH . '/autoload.php'); // this loads MongoDB\Client class

$con = new MongoDB\Client("mongodb://localhost:27017");

MongoDB and the functions.php

  • The repository of all of the applications’ functions is the fuctions.php.
function the_url($script_path){
// add the leading '/' if not parent
if($script_path[0] != '/'){
$script_path = "/" . $script_path;
}
return WWW_ROOT . $script_path;
}


function uEncode($string=""){
return urlencode($string);
}

function raw_u($string=""){
return rawurlencode($string);
}

function html_special($string=""){
return htmlspecialchars($string);
}


function error_404(){
header($_SERVER["SERVER_PROTOCOL"] . "404 Not Found");
exit();
}

function error_500(){
header($_SERVER["SERVER_PROTOCOL"] . "500 Internal Server Error");
exit();
}

function redirect_to($location){
header("Location: " . $location);
exit;
}


function post_request(){
return $_SERVER['REQUEST_METHOD'] == 'POST';
}

function get_request(){
return $_SERVER['REQUEST_METHOD'] == 'GET';
}


function count_subject(){

$subject_set = $result;

$subject_set=show_all_subjects();
$count = 1;
foreach ($subject_set as $document){
$subject_count = $count++;

}

$countResult=$subject_count + 1;
return $countResult;

}



?>

Use PHP to Show MongoDB Documents

Display documents with the index.php

  • A nice table format layout is what the index.php displays for you.
  • The index.php will display all documents from the database in a table format.
<?php require_once('../../../private/initialize.php'); ?>   // (1)
<?php $page_title = 'Subjects'; ?>                          
<?php include(SHARED_PATH . '/staff_header.php'); ?>        // (2)
<?php $subject_set = show_all_subject();                    // (3)
  1. This will include other required php file if not yet included.
  2. This will included the header.php file in the current php page.
  3. A function call to show all subjects in the page. See below code.
    function show_all_subjects(){

        // USING PHP MONGODB\DRIVER\MANAGER
        global $db;                                             // (1)
        $query = new MongoDB\Driver\Query([]);                  // (2)
        $result = $db->executeQuery("abi_db.subjects", $query); // (3)
        return $result;                                         // (4)
  1. This calls the variable $db from the included php file in the initialize.php for the mongoDB connection.
  2. Instantiate the Query class.
  3. The executeQuery method is used to execute the query. This includes the database abi_db and collection name topics and a query object is passed to this function, on success returns a cursor on an exception thrown otherwise.
  4. $result holds the details of the document in array format.
        // USING PHP LIBRARY
       
        global $con;                        // (1)  
        $db = $con->abi_db;                 // (2)
        $collection = $db->subjects;        // (3)
        $result = $collection->find();      // (4)
        return $result;                     // (5)

    }
  1. This calls the variable $con from the included php file in the initialize.php for the mongoDB connection.
  2. Connect to the database abi_db.
  3. Creates the subjects document if it does not exist.
  4. Finds the document in the collection subjects.
  • Save the function show_all_subjects() in a php file query_functions.php to be able to reuse the same as required.
<div id="content">
    <div class="subjects listing">
        <h1>Subjects</h1>

        <div class="actions">
            <a class="action" href="<?php echo the_url('/staff/subjects/new.php'); ?>">Create New Subjects</a>
        </div>

        <table class="table table-sm table-bordered">
            <thead class="thead-dark">
            <tr>
                <th>#</th>
                <th>Position</th>
                <th>Visible</th>
                <th>Name</th>
                <th scope="col" colspan="3">Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php
                $i = 1;
            foreach($subject_set as $row){ ?>
  • The above code will loop through the $subject_set and put each record in the variable $row

  • Distribute the values in the table cells per row.

                <tr>
                    <td><?php echo $i; ?></td>
                    <td><?php echo html_special("$row->position");?></td>
                    <td><?php echo ("$row->visible") == 1 ? 'true' : 'false'; ?></td>
                    <td><?php echo html_special("$row->topic_name") ;?></td>
                    <td><a class="action" href="<?php echo the_url('/staff/subjects/show.php?id=' . html_special(uEncode("$row->_id")));?>">View</a></td>
  • Click the View to display the document to the other php page using the id of the document as the parameter, this is the show.php.
                    <td><a class="action" href="<?php echo the_url('/staff/subjects/edit.php?id='. html_special(uEncode("$row->_id"))); ?>">Edit</a></td>
  • Click the Edit to edit the document to the other php page using the id of the document as the parameter, this is the edit.php.
                    <td><a class="action" href="<?php echo the_url('/staff/subjects/delete.php?id='. html_special(uEncode("$row->_id")));?>">Delete</a></td>
  • Click the Delete to delete the document.
                </tr>
            <?php $i++;} ?>
            </tbody>
        </table>
    </div>
</div>
    <?php include(SHARED_PATH . '/staff_footer.php'); ?> // This will load the footer of the html page
  • Save the above index.php and navigate to it via browser. The result will resemble something like this.

index.php

Conclusion

In this tutorial, you learned about creating and inserting documents using PHP MongoDB. You discovered how to edit and delete with PHP in MongoDB as well. Remember to set up a project directory structure correctly, it’s important to have the MongoDB version and corresponding driver. The good news is you don’t have to guess at it. The compatibility references are available. Now, you create MongoDB documents using PHP with confidence and agility. Have fun with it.

The complete index.php code

<?php require_once('../../../private/initialize.php'); ?>
<?php $page_title = 'Subjects'; ?>                          
<?php include(SHARED_PATH . '/staff_header.php'); ?>    
<?php $subject_set = show_all_subject();  

<div id="content">
    <div class="subjects listing">
        <h1>Subjects</h1>

        <div class="actions">
            <a class="action" href="<?php echo the_url('/staff/subjects/new.php'); ?>">Create New Subjects</a>
        </div>

        <table class="table table-sm table-bordered">
            <thead class="thead-dark">
            <tr>
                <th>#</th>
                <th>Position</th>
                <th>Visible</th>
                <th>Name</th>
                <th scope="col" colspan="3">Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php
               $i = 1;
           foreach($subject_set as $row){ ?>
                <tr>
                    <td><?php echo $i; ?></td>
                    <td><?php echo h("$row->position");?></td>
                    <td><?php echo ("$row->visible") == 1 ? 'true' : 'false'; ?></td>
                    <td><?php echo h("$row->topic_name") ;?></td>
                    <td><a class="action" href="<?php echo the_url('/staff/subjects/show.php?id=' . html_special(uEncode("$row->_id")));?>">View</a></td>
                    <td><a class="action" href="<?php echo the_url('/staff/subjects/edit.php?id='. html_special(uEncode("$row->_id"))); ?>">Edit</a></td>
                    <td><a class="action" href="<?php echo the_url('/staff/subjects/delete.php?id='. html_special(uEncode("$row->_id")));?>">Delete</a></td>
                </tr>
            <?php $i++;} ?>
            </tbody>
        </table>
    </div>
</div>

Check out Part 1

Check out Part 2

Check out Part 3

Check out Part 4

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.