This tutorial help to understand mongodb connection functionality with php. I will get the result from mongodb database and display into html table grid.This is a beginner tutorial for mongodb and PHP lover.Mongodb is very popular nosql database, and php is a very famous open source language for web scripting.
I am creating simple example to read data from mongodb database.We will parse data using php server side and display into HTML table.
Updated Tutorial – CRUD Operations Using PHP And MongoDB
We will follow following simple steps to connect php to mongodb database using Mongo php driver,Previously i have illustrated how to install mongodb and 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 mongodb server using 'mongod'
command. You can type 'mondod'
in window command line and press enter.If you haven’t install please refer previous tutorial.
Step 2: We will create a index.php
file. Here, We will define connection string for mongodb with php and table listing html code to display records.
Step 3: Creating connection with mongodb and php using below code, Please put below code into top of the index.php
file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?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 below code, Please put below code into body section of the index.php
file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <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 simple listing of all mongodb records into html table.You can add/edit record data using mongodb command line query.I left add,edit and delete functionality from UI side.You can do it yourself.