Using MongoDB with PHP: Getting Started

In the following subsections we shall discuss the PHP MongoDB Database Driver. We also discuss setting up the environment and creating a connection to MongoDB Driver from a PHP script.

1. Overview of the PHP MongoDB Database Driver

The PHP MongoDB Driver provides several classes for connecting to MongoDB and performing CRUD operations. The core classes in the PHP driver are shown in Figure 3-1.

The main core classes are discussed in Table 3-1.


MongoDB server operations may generate exceptions. Some of the main exceptions are illustrated in Figure 3-2.

The main exceptions are discussed in Table 3-2.

2. Setting Up the Environment

We need to install the following software in addition to installing MongoDB server.

  • MongoDB Server
  • PHP
  • PHP Driver for MongoDB

Download and install MongoDB 3.0.5. Add the MongoDB bin directory, for example C:\Program Files\MongoDB\Server\3.0\bin directory to the PATH environment variable. Start the MongoDB server with the following command.

>mongod

The output from the command indicates that the MongoDB server has started as shown in Figure 3-3.

3. Installing PHP

A web server is required for running PHP scripts and PHP 5.4, and later versions include a web server packaged in the PHP installation.

  1. Download PHP 5.5 (5.5.26) VC11 x64 Thread-Safe version of the PHP zip file php-5.5.26-Win32-VCl1-x64.zip from http://windows.php.net/download/.

A later PHP version may also be used. PHP 5.3, 5.4, 5.5 and 5.6 are supported.

The VC11 builds require the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed as a prerequisite.

  1. Extract the php-5.5.26-Win32-VC11-x64.zip file to a directory. A php-5.5.26- Win32-VC11-x64 directory gets created. The directory would be different if a different version is used.
  2. Create a document root directory (C:\php used in this chapter) and copy the files and directories from the php-5.5.26-Win32-VC11-x64 directory to the C:\php directory.
  3. Rename the PHP configuration file php.ini-development or php.ini- production in the root directory of the PHP installation, C:\php, to php.ini.
  4. Start the packaged web server at port 8000 with the following command from the document root directory C:\php directory.

php -S localhost:8000

The output from the command indicates that the Development Server has been started and listening on http://localhost:8000 as shown in Figure 3-4.

  1. Any PHP script copied to the document root directory (C:\php) may be run on the integrated web server. PHP scripts may be copied to a subdirectory of the document root directory and run by including the directory path starting from the document root in the URL. Copy the following script hellomongo.php to the C:\php directory in the document root.

<html>

<head>

<title>PHP Test</title>

</head>

<body>

<?php echo ‘<p>Hello MongoDB</p>’; ?>

</body>

</html>

  1. Run the script with the URL http://localhost:8000/hellomongo.php. The output is shown in Figure 3-5.

4. Installing PHP Driver for MongoDB

The driver version to download is based on the MongoDB version used. The compatibility matrix for PHP MongoDB Driver and MongoDB version is listed in Table 3-3.

As we are using MongoDB 3.0.5, the compatible PHP driver version to download is 1.6.

  1. Download the PHP MongoDB Database Driver from http://pecl.php.net/ package/mongo. As we are using PHP 5.5 we need to download the 5.5 Thread Safe (TS) x64 php_mongo-1.6.10-5.5-ts-vc11-x64.zip file from https://pecl. php.net/package/mongo/1.6.10/windows.
  2. Extract the php_mongo-1.6.10-5.5-ts-vc11-x64.zip file to a directory.
  3. Copy the php_mongo.dll file from the extracted directory to the PHP installation document root directory C:\php.
  4. Add the following configuration to the php.ini file. extension=php_mongo.dll
  5. Restart the PHP web server.

Note In subsequent sections we shall run PHP scripts to connect to MongoDB and run CRUD operations in the server. Before each of the subsequent sections (except as noted), run the following command in Mongo shell to delete the catalog collection from the local database; the Mongo shell may be started with the mongo command:

use local

db.catalog.drop()

we shall be using an empty collection for each of the sections so that document/s from a preceding section are not used, and only the section script is used to demonstrate the php MongoDB Driver.

5. Creating a Connection

Create a PHP script mongoconnection.php in C:\php, the document root. Connect to MongoDB database using the MongoClient constructor as follows.

$connection = new MongoClient();

Without any connection parameters specified in the constructor, a connection to localhost:27017 is established, localhost being the default MongoDB host and 27017 being the default MongoDB port. Output the connection detail.

print ‘Connection: <br/>’;

var_dump($connection);

The following output gets generated.

object(MongoClient)#1 (4) { [“connected”]=> bool(true) [“status”]=> NULL

[“server”:protected]=> NULL [“persistent”:protected]=> NULL }

The [“connected”]=> bool(true) indicates the client script has connected to MongoDB. The write concern may be output using the getWriteConcern() method as follows.

var_dump($connection->getWriteConcern());

The following output indicates the value of w as 1 wtimeout as -1.

array(2) { [“w”]=> int(1) [“wtimeout”]=> int(-1) }

A connection can be obtained using a connection string that must start with mongodb://.

$connection = new MongoClient( “mongodb://localhost:27017” );

Output the read preferences using the getReadPreference() method. The output indicates that the read is directed at the primary member in the replica set, which is also the default.

array(1) { [“type”]=> string(7) “primary” }

List the databases on the server using the listDBs() method. An array consisting of databases information gets output. For each database the name, sizeOnDisk, empty properties get output. The three databases in the example script are catalog, local and test.

array(3) { [“databases”]=> array(3) { [0]=> array(3) { [“name”]=> string(5) “Loc8r”

[“sizeOnDisk”]=> float(83886080) [“empty”]=> bool(false) } [1]=> array(3) { [“name”]=>

string(5) “local” [“sizeOnDisk”]=> float(83886080) [“empty”]=> bool(false) } [2]=> array(3)

{ [“name”]=> string(4) “test” [“sizeOnDisk”]=> float(83886080) [“empty”]=> bool(false) } }

[“totalSize”]=> float(251658240) [“ok”]=> float(1) }

The hostname used in the connection string may also be the IPv4 address as follows. The IPv4 address would be different for different users and may be found using the ipconfig/all command.

$connection = new MongoClient(“mongodb://192.168.1.72:27017”);

All the open connections may be listed using the getConnections() method. The connections info including host, port, and connection type (STANDALONE for the sample connections) get listed.

array(2) { [0]=> array(3) { [“hash”]=> string(24) “localhost:27017;-;.;7284” [“server”]=>

array(4) { [“host”]=> string(9) “localhost” [“port”]=> int(27017) [“pid”]=> int(7284)

[“version”]=> array(4) { [“major”]=> int(3) [“minor”]=> int(0) [“mini”]=> int(5) [“build”]=>

int(0) } } [“connection”]=> array(12) { [“min_wire_version”]=> int(0) [“max_wire_ version”]=>

int(3) [“max_bson_size”]=> int(16777216) [“max_message_size”]=> int(48000000)

[“max_write_batch_size”]=> int(1000) [“last_ping”]=> int(1438358245) [“last_ismaster”]=>

int(1438358245) [“ping_ms”]=> int(0) [“connection_type”]=> int(1) [“connection_type_ desc”]=>

string(10) “STANDALONE” [“tag_count”]=> int(0) [“tags”]=> array(0) { } } } [1]=> array(3) {

[“hash”]=> string(27) “192.168.1.72:27017;-;.;7284” [“server”]=> array(4) { [“host”]=> string(12)

“192.168.1.72” [“port”]=> int(27017) [“pid”]=> int(7284) [“version”]=> array(4) { [“major”]=>

int(3) [“minor”]=> int(0) [“mini”]=> int(5) [“build”]=> int(0) } } [“connection”]=> array(12) {

[“min_wire_version”]=> int(0) [“max_wire_version”]=> int(3) [“max_bson_size”]=> int(16777216)

[“max_message_size”]=> int(48000000) [“max_write_batch_ size”]=> int(1000) [“last_ping”]=>

int(1438358245) [“last_ismaster”]=> int(1438358245) [“ping_ms”]=> int(0) [“connection_type”]=>

int(1) [“connection_type_desc”]=> string(10) “STANDALONE” [“tag_count”]=> int(0) [“tags”]=>

array(0) { } } } }

To close connection/s invoke the MongoClient::close ([ boolean|string $connection ] ) method.

To close all connections invoke the close method with arg true. If an arg is not supplied or is false only the connection on which the method is invoked is closed. A specific connection may be supplied using a connection string. If getConnections() method is invoked subsequent to closing all connections an empty array is listed.

array(0) { }

The PHP script mongoconnection.php is listed:

<?php

$connection = new MongoClient(); // connects to localhost:27017

print ‘Connection: <br/>’;

var_dump($connection); print ‘<br/>’;

print ‘Write Concern: <br/>’;

var_dump($connection->getWriteConcern());

print ‘<br/>’;

$connection = new MongoClient( “mongodb://localhost:27017” );

print ‘Read Preferences: <br/>’;

var_dump($connection->getReadPreference());

print ‘<br/>’;

print ‘List DBs: <br/>’;

var_dump($connection->listDBs());

print ‘<br/>’;

$connection = new MongoClient(“mongodb://192.168.1.72:27017”);

print ‘List Open Connections: <br/>’;

var_dump($connection->getConnections());

print ‘<br/>’;

$connection->close(true);

print ‘List Open Connections: <br/>’;

var_dump($connection->getConnections());

?>

Run the PHP script in the browser using the URL http://localhost:8000/mongoconnection.php. The output from the mongoconnection.php script is shown in Figure 3-6.

6. Getting Database Info

The MongoDB class represents a database. The class instance may be obtained using the selectDB() method in MongoClient or by direct indirection of a database name. Create a PHP script db.php in the C:\php directory. Get a MongoDB instance for the test database as follows.

$connection = new MongoClient();

$db = $connection->test;

Alternatively, the selectDB() method may be used. For example, the following MongoDB instance represents the database local.

$db=$connection->selectDB(“local”);

The selectDB method throws the MongoConnectionException, which must be handled in a try-catch statement. The getCollectionNames(boolean) method in MongoDB gets all the connection names in a database. To get the system collections also invoke the method with arg true.

$collections=$db->getCollectionNames(true);

The collection names may be output as follows.

var_dump($collections);

The db.php script is listed. MongoDB class does not explicitly appear in the db.php script because the return value is assigned to a variable.

<?php

try

{

$connection = new MongoClient();

$db = $connection->test; print ‘Datbase: ‘;

var_dump($db); print ‘<br/>’;

$db=$connection->selectDB(“local”);

$collections=$db->getCollectionNames(true);

print ‘Collections: ‘;

var_dump($collections);

print ‘<br/>’;

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb, is the “mongo” process running?</p>’;

exit();

}

?>

Run the PHP script in a browser with the URL http://localhost:8000/db.php. The collection names listed for the local database include system.indexes and catalog as shown in Figure 3-7. The collections listed could be different for different users.

Source: Vohra Deepak (2015), Pro MongoDB™ Development, Apress; 1st ed. edition.

Leave a Reply

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