January 21, 2013

Retrieving data from MongoDB database using PHP

Previous post I wrote about how to install MongoDB driver on PHP when we are using windows. In linux (I mean Ubuntu) there were no issues on installing that. So after that I want to connect to MongoDB to take data.

<!DOCTYPE html>
<html>
    <head>
        <title>MongoDB Connection</title>
    </head>
    <body>
        <?php
        $m = new MongoClient();
       
        $db = $m->phpdb;
       
        $col = $db->pageind;
       
        $rs = $col->find();
       
        foreach ($rs as $rec)
        {
            echo "<a href='" . $rec['url'] . "'>" . $rec['name'] . "</a><br />";
        }
            ?>
    </body>
</html>

Below Code part I inserted between PHP document. This MongoDB server is not running in auth mode. If your MongoDB is running in auth mode and in different ports, you can specify them with connection string. And my database structure was like this.

Database : phpdb

Collection : pageind

Sample document in a database was like below.

{

_id : 1,

name : “Dedunu Blog”,

url : “http://www.dedunu.info/”

}

No comments:

Post a Comment