Tuesday, April 05, 2016

PHP and MongoDB - I

In our previous Article, we had seen some basic commands of MongoDB in action. Now, we would connect our PHP to MongoDB. 

We already know how to install MongoDB driver for PHP and how to install MongoDB as Windows Services. Next in our PHP file, we start connecting to MongoDB as shown below.

<?php
ini_set('display_errors', 1);

// Let's connect without Authorization
$mongo = new MongoClient();

// GET Connections
$mongoConnections = $mongo->getConnections();

// IF Connection Found
if (false === empty($mongoConnections)) 

   // LIST Databases
   $dbs = $mongo->listDBs();
   
   // Show List of DataBases
   echo "<b>Showing All the DB Names :</b> ";
   foreach($dbs['databases'] as $d)
   {
     $dn = $d['name'];
     echo "<br>Database Name : $dn" ;
 
     // Select the database
     $p = $mongo->{$dn};
 
     // Get all the Collections
     $c = $p->listCollections();
     echo ", Collections are : ";
     foreach($c as $n) 
     {
       echo "[$n] ";
     } 
   }
   
   // Select our Database within the 1
   // position within the $dbs array
   $db = $dbs['databases'][1]['name'];
   $db = $mongo->{$db};
   
   // Select a collection say "myDatabase"
   $col = $db->myDatabase;
   
   // get all records
   $records = $col->find();
   
   // Iterate and show
   foreach($records as $key=>$val)
   {
     echo "<br>First Name : " . $val['fname'] . 
          ", Last Name : " . $val['lname'] . 
          ", Roll : " . $val['roll'] . 
          ", Status : " . $val['status']  ;
   }
   
   // INSERT a new ROW in that Collection
   // Insert a Document to Collection
   $arr =  array('fname' => 'Amiya', 'lname' => 'Sengupta', 
                 'roll' => '33', 'status' => '4');
   $col->insert($arr);
   
   
   // If we want to create a New Collection, JUST
   // use its name, Mongo will automatically create it
   $col = $db->PassedStudents;
   
   // Insert a Document to Collection
   $arr =  array('fname' => 'Adhuna', 'lname' => 'Muland', 
                 'roll' => '10', 'status' => '3');
   $result = $col->insert($arr);
   
   // Check if INSERT was successful
   if($result['ok'] != 1)
    echo " INSERT ERROR";
   
   // CREATE A NEW COLLECTION called 'Publisher'
   $publisher = $db->createCollection(
      "publisher",
       array(
        'capped' => true,
        'size' => 10*1024,
        'max' => 10
      )
   );
   
   // Insert some records in Publisher
   $arr =  array(
           'name' => 'General Publisher', 
           'address' => '10, Peter Road, Zip 2343', 
           'phone' => '9876543210');
   $result = $publisher->insert($arr);   
   

else 
{
   // Not connected
   echo "MongoDB not connected";
}
?>

The above code is quite self-explanatory. We have the MongoClient object available with us. This object helps us to interact with MongoDb database.

Some points which need to be noticed here are : 
1. listDBs() gets all the Database available. This is equivalent to "show dbs" command in Mongo Shell.
2. listCollections() gets all the collections available within the database. 
3. find() is used to find all records within a collection. The find() method returns a MongoCursor object 
4. insert() is used to INSERT record into collection

Check the output below :: 




In our next article, we'll see various ways of querying Mongo.