This tutorial help to understand MongoDB connection functionality with PHP. I will get the result from MongoDB database and display it in an HTML table grid.
This is a beginner tutorial for mongodb and PHP lover. MongoDB is a very popular NoSQL database, and PHP is a very famous open-source language for web scripting.
I am creating a simple example to read data from MongoDB database. We will parse data using PHP server side and display it into an HTML table.
Updated Tutorial – CRUD Operations Using PHP And MongoDB
We will follow the following simple steps to connect PHP to MongoDB database using Mongo PHP driver, Previously I have illustrated how to install mongodb driver in your xampp windows server.
You can also check other tutorial of MongoDB and PHP,
Simple Listing Example of MongoDB with PHP
Step 1: We will start the MongoDB server using 'mongod'
command. You can type 'mondod'
in window command line and press enter. If you haven’t installed please refer previous tutorial.
Step 2: We will create a index.php
file. Here, We will define the connection string for MongoDB with PHP and table listing HTML code to display records.
Step 3: Create a connection with MongoDB and PHP using the below code, Please put the below code on the top of the index.php
file.
<?php // Config $dbhost = 'localhost'; $dbname = 'testdb'; // Connect to test database $m = new Mongo("mongodb://$dbhost"); $db = $m->dbname; // select the collection $collection = $db->movie; // pull a cursor query $cursor = $collection->find(); ?>
Step 4: Iterating on MongoDB result set using for-each
loop using the below code, Please put the below code into the body section of the index.php
file.
<table class=""> <thead> <tr> <th>Name</th> <th>Age</th> <th>roll Number</th> </tr> </thead> <tbody> <?php foreach ($cursor as $document) {?> <tr> <th><?php echo $document['name']?></th> <th><?php echo $document['age']?></th> <th><?php echo $document['rno']?></th> </tr> <?php }?> </tbody> </table>
Conclusion
This PHP MongoDB tutorial help to display a simple listing of all MongoDB records into HTML table.You can add/edit record data using the MongoDB command line query. I left add, edit and delete functionality from UI side.You can do it yourself.