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.
1 | pecl search mongo |
- It should look similar to this.
1 2 3 4 5 | .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.
1 | php --version |
- You should see something like this.
1 2 3 4 | 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 Driver | MongoDB 4.0 | MongoDB 3.6 | MongoDB 3.4 | MongoDB 3.2 | MongoDB 3.0 | MongoDB 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 Driver | PHP 5.4 | PHP 5.5 | PHP 5.6 | PHP 7.0 | PHP 7.1 | PHP 7.2 | PHP 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
.
1 2 | sudo systemctl start mongod sudo systemctl status mongod |
- This is what it should look like or something similar to it.
1 2 3 4 5 6 7 8 9 10 | ● 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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.
1 2 3 4 5 6 7 | // 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 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.
1 2 3 4 | <?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) |
- This will include other required php file if not yet included.
- This will included the
header.php
file in the current php page. - A function call to show all subjects in the page. See below code.
1 2 3 4 5 6 7 | 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) |
- This calls the variable
$db
from the included php file in theinitialize.php
for the mongoDB connection. - Instantiate the Query class.
- The
executeQuery
method is used to execute the query. This includes the databaseabi_db
and collection nametopics
and a query object is passed to this function, on success returns acursor
on an exception thrown otherwise. $result
holds the details of the document in array format.
1 2 3 4 5 6 7 8 9 | // USING PHP LIBRARY global $con; // (1) $db = $con->abi_db; // (2) $collection = $db->subjects; // (3) $result = $collection->find(); // (4) return $result; // (5) } |
- This calls the variable
$con
from the included php file in theinitialize.php
for the mongoDB connection. - Connect to the database
abi_db
. - Creates the subjects document if it does not exist.
- Finds the document in the collection
subjects
.
- Save the
function show_all_subjects()
in a php filequery_functions.php
to be able to reuse the same as required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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> |
1 2 3 | <?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.
1 2 3 4 5 |
1 |
- 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.
1 |
- 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.
1 |
- Click the Delete to delete the document.
1 | <?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.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <?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> |
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started