How to Retrieve MongoDB Document using PHP Part 3
Introduction
In MongoDB, the importance of CRUD (Create, Read, Update, Delete) is highly valued. Before you can update a document, you must retrieve it. Here, in part 3 of the series, you’ll learn about updating documents using PHP. You’ll also discover the line details of the PHP script and why it’s so important to code correctly. Begin now and find out how to confidently retrieve and edit documents with this step-by-step tutorial.
Prerequisites
MongoDB – Install the latest version that is compatible with your OS.
MongoDB PHP Driver – Install the correct PHP driver that is recommended for your version of MongoDB.
Check your MongoDB driver with the
pecl searchcommand:
1 | pecl search mongo |
- It should look close to this:
1 2 3 4 5 6 7 8 9 | .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 |
- Find out what version of PHP is installed. Use the
php --versioncommand at the command line:
1 | php --version |
- Here is a similar result of what you should see.
1 2 3 4 5 6 7 | 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 |
Use the command line to start MongoDB
Press Ctrl+Alt+T to access your terminal.
Give permissions to start MongoDB by using the
sudocommand.
1 2 3 | sudo systemctl start mongod sudo systemctl status mongod |
- This is similar to what should appear.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ◠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) |
>NOTE: This is the 3rd part of a series in the tutorial on how to retrieve MongoDB document using PHP. Before continuing on with this part of the series, review parts 1 and 2. Verify that you have installed MongoDB and the associated driver correctly.
About the Page – Edit.php
- The Edit.php page is where you’ll find the details of a document. It’s also where you can update and save fields in the database.
Verify the id with a script
- Use this script to make sure the
idparameter setting is correct. A false result redirects to the page calledindex.php.
1 2 3 4 5 6 7 8 9 10 11 | <?php require_once('../../../private/initialize.php'); // (1) if(!isset($_GET['id'])){ // (2) redirect_to(url_for('/staff/subjects/index.php')); } $id = $_GET['id']; // (3) |
(1) You just need to add initialize.php one time.
(2) The superglobals $_GET is where you can get the id. Redirect the id to index.php.
(3) A variable $id is the superglobals value setting.
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 | if(is_post_request()){ $subject = []; // (4) $subject['id'] = $id; $subject['topic_name'] = $_POST['topic_name'] ?? ''; $subject['position'] = $_POST['position'] ?? ''; $subject['visible'] = $_POST['visible'] ?? ''; edit_subject($subject); // (5) }else{ $result = find_subject_by_id($id); // (6) // $subject_set =[]; // (7) $subject_set = show_all_subjects(); $count = 1; foreach ($subject_set as $document){ $subject_count = $count++; } } ?> |
(4) The superglobals $_POST values to $subject if it is a POST request. Then it passes to edit_subject($subject);
(5) The document is updated with values using edit_subject($subject);
(6) To show which values to edit, call the find_subject_by_id($id) function.
(7) All subjects (documents) are counted.
About the `edit_subject($subject)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function edit_subject ($subject){ // Using the MongoDBDriverManager global $db; // (1) $id= $subject['id']; // (2) $updateRec = new MongoDBDriverBulkWrite; // (3) $updateRec->update( // (4) ['_id'=>new MongoDBBSONObjectID($id)], ['$set' => [ 'menu_name' =>$subject['menu_name'], 'position'=>$subject['position'], 'visible'=>$subject['visible'] ]], ['multi' => false, 'upsert' => false] // (5) ); $writeConcern = new MongoDBDriverWriteConcern( // (6) MongoDBDriverWriteConcern::MAJORITY, 1000); $result = $db->executeBulkWrite( 'globe_bank.subjects', $updateRec, $writeConcern ); |
(1) To connect MongoDB, the initialize.php includes the $db call variable and calls it.
(2) The $subject array has $id, which holds its value.
(3) The variable $updateRec has the MongoDBDriverBulkWrite assigned to it.
(4) Thetopic_name, position, and visible are the field values the $set operator modifies after the execution of the update operator.
(5) So that a new document isn’t created, “false” is the setting of upsert. Only the existing document is updated if multi has a false setting. If multi is something other than false, all documents are updated based on specifics outlined in the criteria.
(6) The majority levels that are successful are indicated by WriteConcern.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Using the PHP Library global $con; // (1) $db = $con->abi_db; // (2) $collection = $db->subjects; // (3) $updateResult = $collection->updateOne( // (4) ['_id'=>new MongoDBBSONObjectID($id)], ['$set' => [ 'topic_name' =>$subject['topic_name'], 'position'=>$subject['position'], 'visible'=>$subject['visible'] ]], ['multi' => false, 'upsert' => false] // (5) ); |
(1) To connect MongoDB, the initialize.php includes the $con call variable and calls it.
(2) The MongoDBBSONObjectID is used to match an ObjectId value to an id.
(3) The collection called $subject and the database abi_db connects.
(4) The topic_name, position, and visible are the field values the $set operator modifies after the execution of the update operator.
(5) So that a new document isn’t created, “false” is the setting of upsert. Only the existing document gets updated if multi has a false setting. If multi is set to anything else, it is updating documents using PHP (all documents) based on specific criteria. In this case, the multi setting is set to false.
1 2 3 4 | if($result){ redirect_to(the_url('/staff/subjects/show.php?id=' . $id)); } } |
View the edits that were made with a redirect to
show.phppage.Use the same specifications by saving a
query_functions.phpfile with thefunction edit_subject($subject)included.
1 2 3 4 5 6 7 8 | <?php $page_title = 'Edit Subject'; ?> <?php include(SHARED_PATH . '/staff_header.php'); ?> [**""> « Back to the List**](https://intern.textbroker.com/a/teamorder-write-submit.php) # Edit Subject |
- Here below, the
$rowvariable is where the details of the results are stored.
1 2 | <?php foreach($result as $row){ ?> |
1 2 3 4 5 6 7 8 9 10 11 |
- The number of documents within the collection are counted with the
<select>tag script.
1 2 3 4 5 6 7 8 | <?php for($i=1; $i <= $subject_count; $i++){ echo ""<option value="""{$i}"""";" if(html_special($row-="if(html_special($row-">position) == $i){ echo ""selected""; } echo "">{$i}</option>""; } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
1 | <?php include(SHARED_PATH . '/staff_footer.php'); ?> // This will load the footer of the html page |
Save the script and name it
edit.php.View the page by going to the
index.phppage and then clicking the “Edit” link. It should like something like this:

Conclusion
In this tutorial, part 3 in the series, you discovered the line values of what constitutes the edit.php script. You’ve also gained a better understanding of the code behind updating documents using PHP. Sometimes it helps to visualize how it looks all put together; therefore, for your convenience, the entire script for the edit.php page is shown below.
The full script for the edit.php page
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | <?php require_once('../../../private/initialize.php'); if(!isset($_GET['id'])){ redirect_to(the_url('/staff/subjects/index.php')); } $id = $_GET['id']; if(is_post_request()){ $subject = []; $subject['id'] = $id; $subject['topic_name'] = $_POST['topic_name'] ?? ''; $subject['position'] = $_POST['position'] ?? ''; $subject['visible'] = $_POST['visible'] ?? ''; edit_subject($subject); }else{ $result = find_subject_by_id($id); $subject_set =[]; $subject_set = show_all_subjects(); $count = 1; foreach ($subject_set as $document){ $subject_count = $count++; } } ?> <?php $page_title = 'Edit Subject'; ?> <?php include(SHARED_PATH . '/staff_header.php'); ?> <![if !supportLineBreakNewLine]> <![endif]> [**""> « Back to the List**](https://intern.textbroker.com/a/teamorder-write-submit.php) # Edit Subject <?php foreach($result as $row){ ?> <form action="" <?php="<?php" echo="echo" the_url('/staff/subjects/edit.php?id=" . h(u($id))); ?">"" method=""post""> <label>Menu Name</label> topic_name); ?>"" /> <label>Position</label> <select name=""position""> <?php for($i=1; $i <= $subject_count; $i++){ echo ""<option value="""{$i}"""";" if(h($row-="if(h($row-">position) == $i){ echo ""selected""; } echo "">{$i}</option>""; } ?> </select> visible == ""1"") {echo "" checked"";} ?>/> <label for=""defaultCheck1"">Visible</label> </form> <?php } ?> <?php include(SHARED_PATH . '/staff_footer.php'); ?> |
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started


