A PHP program to fetch data from a collection in MongoDB database using cursors

December 27, 2012

In our previous article titled “A PHP program to insert individual and batch data into MongoDB database“, we have created a php program to insert data into MongoDB database.

In this article, we will create a php program to fetch the data and display it in a web browser.

The development environment for this application include Apache 2.2.22, PHP 5.3.10 and MongoDB 2.2.2

1. Create a PHP file namely “students_select.php”¬† in the document root of the web server and add the given below php code

    User name : admu
    Password : new_pass
    MongoDB host : localhost
    MongoDB port : 27017
    Database : university
    $server = "mongodb://admu:new_pass@localhost:27017/university";

        // Connecting to server
        $c = new MongoClient( $server );
    }catch(MongoConnectionException $connectionException){
        print $connectionException;

    $data  = "<table style='border:1px solid red;";
    $data .= "border-collapse:collapse' border='1px'>";
    $data .= "<thead>";
    $data .= "<tr>";
    $data .= "<th>Name</th>";
    $data .= "<th>Age</th>";
    $data .= "<th>Course</th>";
    $data .= "<th>Marks</th>";
    $data .= "</tr>";
    $data .= "</thead>";
    $data .= "<tbody>";

        $db = $c->university;
        $collection = $db->students;
        $cursor = $collection->find();
        foreach($cursor as $document){
            $data .= "<tr>";
            $data .= "<td>" . $document["name"] . "</td>";
            $data .= "<td>" . $document["age"]."</td>";
            $data .= "<td>" . $document["course"]."</td>";
            $data .= "<td>" . $document["marks"]."</td>";
            $data .= "</tr>";
        $data .= "</tbody>";
        $data .= "</table>";
        echo $data;

    }catch(MongoException $mongoException){
        print $mongoException;

2. Open the program “students_select.php” with its URL in a web browser to fetch data from MongoDB database and display it in a web browser

Fetching data from MongoDB database using PHP

Figure 1 : Fetching data from MongoDB database using PHP

3. Download PHP program

4. What is next?

A php program to update existing MongoDB data is available at “A PHP program to update collection data in MongoDB database with upsert option“.


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs

Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :

Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner