Getting Started with PHP and MongoDB

ScaleGrid is a MongoDB management solution for public clouds. MongoDB (from “humongous”) is a scalable, high-performance, open source NoSQL database by 10gen.

ScaleGrid will help you provision, configure high availability and disaster recovery, deprovision, monitor, upgrade, clone, backup and recover your MongoDB deployments on AWS, Azure, and DigitalOcean. One of the advantages of ScaleGrid is that it gives you full SSH access to your instances. This enables you to run your PHP server on the same machine as your MongoDB server, an extremely useful benefit for dev and test scenarios. In this tutorial, we’ll show you in five simple steps how to setup your PHP server and MongoDB server on the same machine.

  1. Create your MongoDB Instance on ScaleGrid

    Follow the getting started directions here to create your machine pool, create MongoDB instances, retrieve SSH credentials and SSH into the instance, or check out our Create a MongoDB Cluster documentation.

  2. Connect to MongoDB and Populate Your Data

    SSH into your MongoDB instance. Connect to your local MongoDB instance using the built-in mongo client and fire off some queries:

    
    /usr/bin/mongo
    MongoDB shell version: 2.0.7
    connecting to: test
    >show dbs
    config  (empty)
    local   (empty)
    >db.version()
    2.0.7
    >db.stats()
    {
    "db" : "test",
    "collections" : 0,
    "objects" : 0,
    "avgObjSize" : 0,
    "dataSize" : 0,
    "storageSize" : 0,
    "numExtents" : 0,
    "indexes" : 0,
    "indexSize" : 0,
    "fileSize" : 0,
    "nsSizeMB" : 0,
    "ok" : 1
    }
    

    Let’s create a dummy database and insert some data into a collection. “Collections” are the equivalent of relational tables. A collection can contain many “documents” which is the equivalent of rows in the relational world.

    >use testdb
    switched to db testdb
    >db.testcollection.insert({"name":"blah", "value":"humbug"});
    >db.testcollection.insert({"name":"blah1", "value":"humbug1"});
    >db.find();
    { "_id" : ObjectId("50db292013d7f5d141a9cbfb"), "name" : "blah", "value" : "humbug" }
    { "_id" : ObjectId("50db292913d7f5d141a9cbfc"), "name" : "blah1", "value" : "humbug1" }
    
  3. Setup Your PHP Server

    If you already have a PHP server running on a machine separate from your MongoDB server, you can skip this step and move to step 4. If you don’t have a PHP server, you can install a PHP server on the MongoDB machine. This is one of the benefits of having full SSH access to your MongoDB machines:

    [root@ip-10-29-173-18 ~]#yum install httpd php
    [root@ip-10-29-173-18 ~]#chkconfig httpd on
    [root@ip-10-29-173-18 ~]#service httpd start
    
  4. Install the Mongo PHP Extension

    MongoDB support in PHP is through the Mongo PHP extension. You can  install it using the PECL installer:

    [root@ip-10-29-173-18 ~]#yum install php-pear
    [root@ip-10-29-173-18 ~]#yum install php-devel
    [root@ip-10-29-173-18 ~]#yum install make
    [root@ip-10-29-173-18 ~]#pecl install mongo
    [root@ip-10-29-173-18 ~]#echo "extension=mongo.so" >> /etc/php.ini
    [root@ip-10-29-173-18 ~]#/etc/init.d/httpd restart
    
  5. Run PHP Code

    Retrieve the MongoDB connection string from the ScaleGrid console in the details tab at the bottom of the screen.  If you’re running your PHP code on the same box, you can use 127.0.0.1.

    Let’s write some PHP code to query the documents in the collection we just created. Create a file called test.php and put the code below into the file. Run the code using “php test.php”.

    <?php
    try {
      // open connection to MongoDB server
      $conn = new Mongo('<connection string>');
    
      // access database
      $db = $conn->testdb;
    
      // access collection
      $collection = $db->testcollection;
    
      // execute query
      // retrieve all documents
      $cursor = $collection->find();
    
      // iterate through the result set
      // print each document
      echo $cursor->count() . ' document(s) found.
    ';
      foreach ($cursor as $obj) {
        echo 'Name: ' . $obj['name'] . '
    ';
        echo 'Value: ' . $obj['value'] . '
    ';
        echo '
    ';
      }
    
      // disconnect from server
      $conn->close();
    } catch (MongoConnectionException $e) {
      die('Error connecting to MongoDB server');
    } catch (MongoException $e) {
      die('Error: ' . $e->getMessage());
    }
    
    ?>
    

For more detailed instructions and examples refer to the 10gen documentation on using PHP with Mongo.

 


Dharshan is the founder of ScaleGrid.io (formerly MongoDirector.com). He is an experienced MongoDB developer and administrator. He can be reached for further comment at @dharshanrg


0 Shares
+1
Tweet
Share
Share
Pin