Getting Started with PHP and MongoDB®

3 min read
Big data center concept, cloud database, server power station of the future. Data transfer technology. Synchronization of personal information. Cube or box Block chain of abstract financial data. 3d render.
Getting Started with PHP and MongoDB®

SHARE THIS ARTICLE

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.

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.

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" }

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

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

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 the database
  $db = $conn->testdb;

  // Access the collection
  $collection = $db->testcollection;

  // Execute the query
  // Retrieve all documents
  $cursor = $collection->find();

  // Iterate through the result set
  // Print each document
  echo $cursor->count() . ' document(s) found.' . PHP_EOL;
  foreach ($cursor as $obj) {
    echo 'Name: ' . $obj['name'] . PHP_EOL;
    echo 'Value: ' . $obj['value'] . PHP_EOL;
    echo PHP_EOL;
  }

  // Disconnect from the 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 MongoDB®.

 

For more information, please visit www.scalegrid.io. Connect with ScaleGrid on LinkedIn, X, Facebook, and YouTube.
Table of Contents

Stay Ahead with ScaleGrid Insights

Dive into the world of database management with our monthly newsletter. Get expert tips, in-depth articles, and the latest news, directly to your inbox.

Related Posts

message communication network

What Is RabbitMQ: Key Features and Uses

RabbitMQ is an open-source message broker that simplifies inter-service communication by ensuring messages are effectively queued, delivered, and processed across...

Intro to Redis Sharding

Grasping the concept of Redis sharding is essential for expanding your Redis database. This method involves splitting data over various...

Redis vs Memcached in 2024

Choosing between Redis and Memcached hinges on specific application requirements. In this comparison of Redis vs Memcached, we strip away...

NEWS

Add Headline Here