How to Perform CRUD in MongoDB Document using PHP Part 2

Introduction

If you’re using MongoDB to store data, you’ll need to be able to perform common operations such as reading, updating and deleting documents. These tasks are quick and simple to accomplish using PHP, as long as your version of PHP is compatible and properly configured. In this step-by-step tutorial, we’ll look at an example of showing a MongoDB document using its id using PHP.

How to Update MongoDB Document using PHP

Prerequisites:

Before we attempt to perform any MongoDB operations in PHP, it’s important to make sure certain prerequisites are in place. A few key system requirements include:

  • MongoDB and the MongoDB PHP driver must be properly configured beforehand.

  • To verify that the MongoDB driver is installed, use the following command:

pecl search mongo

You should see a response similar to this:

Package Stable/(Latest) Local
mongo 1.6.16 (stable) MongoDB database driver
mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • To determine what PHP version is installed on your system, use the command shown below:
php --version

The output should look 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

Starting the MongoDB Database Daemon.

Once you’ve confirmed that the system requirements in place, you can start up the MongoDB database daemon.

  • First, open your terminal by pressing Ctrl + Alt + T.

  • Start the MongoDB service and check the status using the command shown below. Using the sudo command will prevent permission-related issues that you might encounter while starting the MongoDB service:

sudo systemctl start mongod
sudo systemctl status mongod

You should see something like this:

Image from Gyazo

NOTE: * Make sure that you completed the tasks described in Part 1 of this series in order to move forward with the steps listed in this second part of this series.

The show.php page

The page shown below will show the details of the document you’re interested in viewing via a form:

<?php
require_once('../../../private/initialize.php'); // (1)
$id = $_GET['id'];                               // (2)
$result=find_subject_by_id($id);                 // (3)  
?>
<?php $page_title = 'Show Subject'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?> // Loads the page header
  1. Include the initialize.php only once.
  2. Get the id from superglobals $_GET.
  3. A function call to show the document in the page using id as its reference.

NOTE : This code can be found in the query_functions.php.

 function find_subject_by_id($id){

        // MongoDB\Driver\Manager
        global $db;                                                // (1)
        $options = [ ];                                            // (2)
        $filter = ['_id' => new MongoDB\BSON\ObjectID( $id )];     // (3)
        $query = new MongoDB\Driver\Query($filter, $options);      // (4)
        $result = $db->executeQuery("abi_db.subjects", $query);    // (5)
        return $result;                                            // (6)
  1. This calls the variable $con from the included php file in the initialize.php for the mongoDB connection.
  2. $options can hold parameters to fine tune the query.
  3. When matching an _id with an ObjectId value the user must use MongoDB\BSON\ObjectID
  4. Instantiate the Query class.
  5. 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.
  6. $result holds the details of the document in array format.
        // PHP Library
        global $con;                                        // (1)
        $filter = ( new MongoDB\BSON\ObjectID( $id ));      // (2)
        $db = $con->abi_db;                                 // (3)
        $collection = $db->subjects;                        // (4)
        $result = $collection->find(['_id'=> $filter]);     // (5)
        return $result;                                     // (6)
    }
  1. This calls the variable $con from the included php file in the initialize.php for the mongoDB connection.
  2. When matching an _id with an ObjectId value the user must use MongoDB\BSON\ObjectID.
  3. Connect to the database abi_db.
  4. Creates the subjects document if it does not exist.
  5. Finds the document in the collection subjects that matches the value of the _id.
  6. This holds the details for the collection found from the query.
  • Save the function find_subject_by_id($id) in a php file query_functions.php to be able to reuse the same as required.
<div id="content">
    <a class="back-link" href="<?php echo the_url('/staff/subjects/index.php'); ?>"> « Back to the List</a>

    <div class="subject show">
  • The below script loops through the $result variable and store the details in $row variable.
        <?php foreach($result as $row){ ?>
        <!-- This wil display the value of menu_name field from the document -->
        <h1>Subject: <?php echo h("$row->menu_name");?> </h1>
       
        <div class="attributes">
            <dl>
                <dt>Menu Name</dt>
                <!-- This wil display the value of menu_name field from the document -->
                <dd><?php echo h("$row->menu_name");?></dd>
            </dl>
            <dl>
                <dt>Position</dt>
                <!-- This wil display the value of position field from the document -->
                <dd><?php echo h("$row->position");?></dd>
            </dl>

            <dl>
                <dt>Visible</dt>
                <!-- This wil display the value of visible field from the document -->
                <dd><?php echo h("$row->visible");?></dd>
            </dl>
           
        </div>
        <?php } ?>
    </div>
</div>
<?php include(SHARED_PATH . '/staff_footer.php'); ?> // This will load the footer of the html page
  • Save the above as show.php.

  • To see this php page, click the View link in the index.php page. The result will resemble something like this.

Show.php page

Conclusion:

When you’re working with data in MongoDB, retrieving a document in order to view its details is a common task. It’s easy to show a MongoDB document in PHP, as long as you have its id for reference. Armed with the code provided in this article as an example, you should have no trouble showing a MongoDB document using its id using PHP.

The entirety of the code

<?php

require_once('../../../private/initialize.php');

if(!isset($_GET['id'])){
    redirect_to(url_for('/staff/pages/index.php'));
}

$id = $_GET['id'];

$result=find_subject_by_id($id);


?>

<?php $page_title = 'Show Subject'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?>

<div id="content">
    <a class="back-link" href="<?php echo the_url('/staff/subjects/index.php'); ?>"> « Back to the List</a>

    <div class="subject show">
        <?php foreach($result as $row){ ?>
        <h1>Subject: <?php echo h("$row->topic_name");?> </h1>
       
        <div class="attributes">
            <dl>
                <dt>Menu Name</dt>
                <dd><?php echo h("$row->topic_name");?></dd>
            </dl>
            <dl>
                <dt>Position</dt>
                <dd><?php echo h("$row->position");?></dd>
            </dl>

            <dl>
                <dt>Visible</dt>
                <dd><?php echo h("$row->visible");?></dd>
            </dl>
           
        </div>
        <?php } ?>
    </div>
</div>

<?php include(SHARED_PATH . '/staff_footer.php'); ?>

Check out Part 1

Check out Part 2

Check out Part 3

Check out Part 4

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.