Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
PHP and MongoDB Web Development Beginner's Guide
PHP and MongoDB Web Development Beginner's Guide

PHP and MongoDB Web Development Beginner's Guide: Combine the power of PHP and MongoDB to build dynamic web 2.0 applications

$48.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (11 Ratings)
Paperback Nov 2011 292 pages 1st Edition
eBook
$26.09 $28.99
Paperback
$48.99
$48.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (11 Ratings)
Paperback Nov 2011 292 pages 1st Edition
eBook
$26.09 $28.99
Paperback
$48.99
eBook
$26.09 $28.99
Paperback
$48.99

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

PHP and MongoDB Web Development Beginner's Guide

Chapter 1. Getting Started with MongoDB

We are about to begin our journey in PHP and MongoDB web development. Since you picked up this book, I assume you have some background building web apps using PHP, and you are interested in learning to develop PHP applications with MongoDB as data backend. In case you have never heard of MongoDB before, it is an open source, document-oriented database that supports the concept of flexible schema. In this chapter, we will learn what MongoDB is, and what do we gain from using MongoDB instead of trusted old SQL databases. We will start by learning briefly about the NoSQL databases (a set of database technologies that are considered alternative to RDBM systems), the basics of MongoDB, and what distinguishes it from relational databases. Then we will move on to installing and running MongoDB and hooking it up with PHP.

To sum it up, in this chapter we will:

  • Learn about the NoSQL movement

  • Learn the basic concepts behind MongoDB

  • Learn how to download, install, and run MongoDB on a computer

  • Learn to use the mongo Interactive Shell

  • Learn how to make PHP and MongoDB talk to each other

So let's get on with it...

The NoSQL movement

You probably have heard about NoSQL before. You may have seen it in the RSS feed headlines of your favorite tech blogs, or you overheard a conversation between developers in your favorite restaurant during lunch. NoSQL (elaborated "Not only SQL"), is a data storage technology. It is a term used to collectively identify a number of database systems, which are fundamentally different from relational databases. NoSQL databases are increasingly being used in web 2.0 applications, social networking sites where the data is mostly user generated. Because of their diverse nature, it is difficult to map user-generated content to a relational data model, the schema has to be kept as flexible as possible to reflect the changes in the content. As the popularity of such a website grows, so does the amount of data and the read-write operations on the data. With a relational database system, dealing with these problems is very hard. The developers of the application and administrators of the database have to deal with the added complexity of scaling the database operations, while keeping its performance optimum. This is why popular websites—Facebook, Twitter to name a few—have adopted NoSQL databases to store part or all of their data. These database systems have been developed (in many cases built from scratch by developers of the web applications in question!) with the goal of addressing such problems, and therefore are more suitable for such use cases. They are open source, freely available on the Internet, and their use is increasingly gaining momentum in consumer and enterprise applications.

Types of NoSQL databases

The NoSQL databases currently being used can be grouped into four broad categories:

  • Key-value data stores: Data is stored as key-value pairs. Values are retrieved by keys. Redis, Dynomite, and Voldemort are examples of such databases.

  • Column-based databases: These databases organize the data in tables, similar to an RDBMS, however, they store the content by columns instead of rows. They are good for data warehousing applications. Examples of column-based databases are Hbase, Cassandra, Hypertable, and so on.

  • Document-based databases: Data is stored and organized as a collection of documents. The documents are flexible; each document can have any number of fields. Apache CouchDB and MongoDB are prominent document databases.

  • Graph-based data-stores: These databases apply the computer science graph theory for storing and retrieving data. They focus on interconnectivity of different parts of data. Units of data are visualized as nodes and relationships among them are defined by edges connecting the nodes. Neo4j is an example of such a database.

Chapter 1. Getting Started with MongoDB

We are about to begin our journey in PHP and MongoDB web development. Since you picked up this book, I assume you have some background building web apps using PHP, and you are interested in learning to develop PHP applications with MongoDB as data backend. In case you have never heard of MongoDB before, it is an open source, document-oriented database that supports the concept of flexible schema. In this chapter, we will learn what MongoDB is, and what do we gain from using MongoDB instead of trusted old SQL databases. We will start by learning briefly about the NoSQL databases (a set of database technologies that are considered alternative to RDBM systems), the basics of MongoDB, and what distinguishes it from relational databases. Then we will move on to installing and running MongoDB and hooking it up with PHP.

To sum it up, in this chapter we will:

  • Learn about the NoSQL movement
  • Learn the basic concepts behind MongoDB
  • Learn how to download, install, and run MongoDB on a computer
  • Learn to use the mongo Interactive Shell
  • Learn how to make PHP and MongoDB talk to each other

So let's get on with it...

The NoSQL movement

You probably have heard about NoSQL before. You may have seen it in the RSS feed headlines of your favorite tech blogs, or you overheard a conversation between developers in your favorite restaurant during lunch. NoSQL (elaborated "Not only SQL"), is a data storage technology. It is a term used to collectively identify a number of database systems, which are fundamentally different from relational databases. NoSQL databases are increasingly being used in web 2.0 applications, social networking sites where the data is mostly user generated. Because of their diverse nature, it is difficult to map user-generated content to a relational data model, the schema has to be kept as flexible as possible to reflect the changes in the content. As the popularity of such a website grows, so does the amount of data and the read-write operations on the data. With a relational database system, dealing with these problems is very hard. The developers of the application and administrators of the database have to deal with the added complexity of scaling the database operations, while keeping its performance optimum. This is why popular websites—Facebook, Twitter to name a few—have adopted NoSQL databases to store part or all of their data. These database systems have been developed (in many cases built from scratch by developers of the web applications in question!) with the goal of addressing such problems, and therefore are more suitable for such use cases. They are open source, freely available on the Internet, and their use is increasingly gaining momentum in consumer and enterprise applications.

Types of NoSQL databases

The NoSQL databases currently being used can be grouped into four broad categories:

  • Key-value data stores: Data is stored as key-value pairs. Values are retrieved by keys. Redis, Dynomite, and Voldemort are examples of such databases.
  • Column-based databases: These databases organize the data in tables, similar to an RDBMS, however, they store the content by columns instead of rows. They are good for data warehousing applications. Examples of column-based databases are Hbase, Cassandra, Hypertable, and so on.
  • Document-based databases: Data is stored and organized as a collection of documents. The documents are flexible; each document can have any number of fields. Apache CouchDB and MongoDB are prominent document databases.
  • Graph-based data-stores: These databases apply the computer science graph theory for storing and retrieving data. They focus on interconnectivity of different parts of data. Units of data are visualized as nodes and relationships among them are defined by edges connecting the nodes. Neo4j is an example of such a database.

MongoDB A document-based NoSQL database

MongoDB falls into the group of document-oriented NoSQL databases. It is developed and maintained by 10gen (http://www.10gen.com). It is an open source database, written in the programming language C. The source code is licensed under AGPL and freely available at GitHub, anyone can download it from the repo https://github.com/mongodb/mongo and customize it to suit his/her needs. It is increasingly being used as a data storage layer in different kinds of applications, both web-based and nonweb-based.

Why MongoDB?

Features that make learning and using MongoDB a win, include:

  • Easy to learn, at least easier than learning other NoSQL systems, if I dare say. Column-oriented or graph-based databases introduce radical ideas that many developers struggle to grasp. However, there is a lot of similarity in the basic concepts of MongoDB and a relational database. Developers coming from an RDBMS background, find little trouble adapting to MongoDB.
  • It implements the idea of flexible schema. You don't have to define the structure of the data before you start storing it, which makes it very suitable for storing non-structured data.
  • It is highly scalable. It comes with great features to help keep performance optimum, while the size and traffic of data grows, with little or no change in the application layer.

It is free, it can be downloaded and used without charge. It has excellent documentation and an active and co-operative online community who participate in mailing lists, forums, and IRC chat rooms.

Who is using MongoDB?

Let's take a look at some real world use cases of MongoDB:

  • Craigslist: Craigslist is the world's most popular website for featuring free classified advertisements. It uses MongoDB to archive billions of records. They had been using a MySQL based solution for achieving that. Replacing them with MongoDB has allowed them to add schema changes without delay, and scale much more easily.
  • Foursquare: Foursquare is a popular location-based social networking application. It stores the geographical location of interesting venues (restaurants, cafes, and so on) and records when users visit these venues. It uses MongoDB for storing venue and user information.
  • CERN: The renowned particle physics laboratory based in Geneva, uses MongoDB as an aggregation cache for its Large Hadron Collider experiment. The results for expensive aggregation queries, performed on massive amounts of data, are stored in MongoDB for future use.

MongoDB concepts—Databases, collections, and documents

A MongoDB server hosts a number of databases. The databases act as containers of data and they are independent of each other. A MongoDB database contains one or more collections. For example, a database for a blogging application named myblogsite may typically have the collections articles, authors, comments, categories, and so on.

A collection is a set of documents. It is logically analogous to the concept of a table in a relational database. But unlike tables, you don't have to define the structure of the data that is going to be stored in the collection beforehand.

A document stored in a collection is a unit of data. A document contains a set of fields or key-value pairs. The keys are strings, the values can be of various types: strings, integers, floats, timestamps, and so on. You can even store a document as the value of a field in another document.

Anatomy of document

Let's take a closer look at a MongoDB document. The following is an example of a document that stores certain information about a user in a web application:

{
_id : ObjectId("4db31fa0ba3aba54146d851a")
username : "joegunchy"
email : "joe@mysite.org"
age : 26
is_admin : true
created : "Sun Apr 24 2011 01:52:58 GMT+0700 (BDST)"
}

The previous document has six fields. If you have some JavaScript experience, you would recognize the structure as JSON or JavaScript Object Notation. The value for the first field, _id, is autogenerated. MongoDB automatically generates an ObjectId for each document you create in a collection and assigns it as _id for that document. This is also unique; that means no two documents in the same collection will have the same values for ID, just like a primary key of a table in a relational database. The next two fields, username and email are strings, age is an integer, and is_admin is boolean. Finally, created is a JavaScript DateTime object, represented as a string.

BSON—The data exchange format for MongoDB

We have already seen that the structure of a document imitates a JSON object. When you store this document in the database, it is serialized into a special binary encoded format, known as BSON, short for binary JSON. BSON is the default data exchange format for MongoDB. The key advantage of BSON is that it is more efficient than conventional formats such as XML and JSON, both in terms of memory consumption and processing time. Also, BSON supports all the data types supported by JSON (string, integer, double, Boolean, array, object, null) plus some special data types such as regular expression, object ID, date, binary data, and code. Programming languages such as PHP, Python, Java, and so on have libraries that manage conversion of language-specific data structures (for example, the associative array in PHP) to and from BSON. This enables the languages to easily communicate with MongoDB and manipulate the data in it.

Note

If you are interested to learn more about BSON format, you may try visiting http://bsonspec.org/.

Similarity with relational databases

Developers with a background on working with relational database systems will quickly recognize the similarities between the logical abstractions of the relational data model and the Mongo data model. The next figure compares components of a relational data model with those of the Mongo data model:

Similarity with relational databases

The next figure shows how a single row of a hypothetical table named users is mapped into a document in a collection:

Similarity with relational databases

Also just like columns of a RDBMS table, fields of a collection can be indexed, although implementations of indexing are different.

So much for the similarities: now let's talk briefly about the differences. The key thing that distinguishes MongoDB from a relational model is the absence of relationship constraints. There are no foreign keys in a collection and as a result there are no JOIN queries. Constraint management is typically handled in the application layer. Also, because of its flexible schema property, there is no expensive ALTER TABLE statement in MongoDB.

Downloading, installing, and running MongoDB

We are done with the theoretical part, at least for now. It is time for us to download, install, and start playing with MongoDB on the computer.

System requirements

MongoDB supports a wide variety of platforms. It can run on Windows (XP, Vista, and 7), various flavors of Linux (Debian/Ubuntu, Fedora, CentOS, and so on), and OS X running on Intel-based Macs. In this section, we are going to see step-by-step instructions for having a MongoDB system up and running in a computer, running on Windows, Linux, or OS X.

Time for action - downloading and running MongoDB on Linux

Now, we are going to learn how to download and run the MongoDB server on a Linux box:

  1. Fire up the terminal program. Type in the following command and hit Enter
    wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.3.tgz > mongo.tgz
    
    
  2. Extract the downloaded archive by using the following command:
    tar xzf mongo.tgz
    
    
  3. Rename the extracted directory by using the following command:
    mv mongodb-linux-i686-1.8.3 mongodb
    
    
  4. Create the data directory /data/db by using the following command:
    sudo mkdir -p /data/db
    sudo chown `id -u` /data/db
    
  5. Startup the server by running the following command:
    ./mongodb/bin/mongod
    
    
    Time for action - downloading and running MongoDB on Linux
  6. Open another tab in the terminal and run the next command:
    ./mongodb/bin/mongo
    
    
  7. Type show dbs into the shell and hit Enter.

What just happened?

In step 1, we downloaded the latest stable release of MongoDB 32-bit version for Linux using the wget program, and stored it as a GZIP tarball named mongo.tgz on your machine.

Note

At the time of this writing, the latest production release for MongoDB is 1.8.3. So when you try this, if a newer production release is available, you should download that version instead.

In steps 2 and 3, we extracted the tarball and renamed the extracted directory to mongodb for convenience. In step 4, we created the data directory /data/db for MongoDB, and gave it permission to read from and write to that directory. In step 5, we startup the MongoDB server by executing the mongodb/bin/mongod script.

In step 6, after we have successfully launched the server, we start the mongo interactive shell:

$./mongodb/bin/mongo
MongoDB shell version: 1.8.1
url: test
connection to test
type "help" for help
>

Once the shell has started, we issue the command show dbs to list all the pre-loaded databases in the server:

>show dbs
local (empty)
admin (empty)
>

The databases listed here are special databases pre-built within the server. They are used for administration and authentication purposes. We do not need to concern ourselves with them right now.

Tip

Installing MongoDB using package managers

You can use the package manager of your Linux distribution (apt for Debian/Ubuntu, yum for Fedora/CentOS) to install MongoDB. To get distro-specific instructions, Ubuntu/Debian users should visit http://www.mongodb.org/display/DOCS/Ubuntu+and+Debian+packages. Users of CentOS and Fedora should visit http://www.mongodb.org/display/DOCS/CentOS+and+Fedora+Packages. The advantage of using a package manager, other than being able to install with fewer commands, is that you can launch the Mongo server and the client just by typing mongod and mongo respectively in the shell.

Installing MongoDB on OS X

The instructions for installing MongoDB on an OS X powered Mac machine are the same as those for Linux. You have to download the OS X specific binaries for Mongo (available at http://www.mongodb.org/downloads), and follow the same steps to execute them.

Alternatively, if you have package managers installed on your OS X (Homebrew or MacPorts), you can use them to install MongoDB.

To install MongoDB with HomeBrew use the following command:

$ brew update
$ brew install mongodb

To use MacPorts to install MongoDB use the following command:

$ sudo port install mongodb

Configuring MongoDB

When we launched the mongod program, it booted up with some default configuration settings, such as the path to the data directory (C:\data\db on Windows or /data/db on Unix). In real world deployments, we want to be able to specify these settings ourselves. There are two ways to achieve that. We can either modify them by supplying command-line parameters to the mongod program at invocation, or by using file-based configurations.

Command-line parameters

We can override the default MongoDB settings by passing command-line parameters to the mongod program. For example, the next command tells MongoDB to use C:\mongodb_data as data directory by sending it as a --dbpath argument:

C:\>mongodb\bin\mongod --dbpath C:\mongodb_data

The following table lists some useful command-line parameters and their functions:

Parameter

What it does

--dbpath

Path to the directory for storing data files.

--bind_ip

IP address that the mongod server will listen on, default is 127.0.0.1.

--port

Port address that mongod will listen on, default is 27017.

--logpath

Full file path to the log file where the MongoDB messages will be written. By default all messages are written to standard output.

--logappend

Setting this option to true appends the messages at the end of the log file. Setting it to false overwrites the log.

We can see the full list of command-line options by running mongod with the--help option:

C:\>mongodb\bin\mongod --help

File-based configuration

An alternative to sending all those command-line parameters to mongod manually is to put the required configuration settings in a file and then pass the path of the file as a--config option. For example, consider the following sample configuration file:

dbpath = D:\mongodb_data
logpath = D:\mongodb.log
logappend = true

We store this file to a location, say C:\mongodb.conf. Now, to start MongoDB with the these settings, we have to enter the next command in the CMD prompt:

C:\>mongodb\bin\mongod --config C:\mongodb.conf

mongod will be loaded with these configuration settings. Note that file-based parameters are the same as those for command-line options.

Note

If you are on a Linux machine, and you have installed Mongo using a package manager, such a configuration file may already exist in your system, typically at the location /etc/mongo.conf. You can modify that file to boot Mongo server with the configuration of your choice.

Have a go hero configure MongoDB to run with non-default settings

Start MongoDB with the following settings, using a file-based configuration:

  • Default data directory at /usr/bin/mongo.
  • Default port address at 8888.
  • Messages will be logged at /var/logs/mongodb.log. The log file should be overwritten over time.

Stopping MongoDB

There are several ways you can shutdown a running MongoDB server.

Hitting Control + C

In the terminal window (or CMD prompt window in case you are on Windows) running the mongod process, hit Ctrl + C. This will signal the server to do a clean shutdown, flush, and close its data files.

From the mongo shell

From the mongo interactive shell, you can issue a shutdownServer() command, causing mongod to terminate:

>use admin
switched to db admin
>db.shutdownServer()

Sending INT or TERM signal in UNIX

In Linux/OS X, you can send a kill -2 <PID> signal to the process running mongod, which will cause the server to shutdown cleanly. You can get the PID by running the following command:

ps -aef | grep mongod

Creating databases, collections, and documents

Now that you have MongoDB up and running on your computer, it is time for us to create some databases, collections, and documents.

Time for action - creating databases, collections, and documents

The next example will demonstrate how to create a database, and insert a document in a collection using the mongo shell program:

  1. In the mongo shell, enter the following command:
    >use myfirstdb
    
    
  2. When the prompt returns, enter the following commands to create documents in a collection named movies:
    >db.movies.insert({name:"Source Code", genre:"sci-fi", year:2011})
    >db.movies.insert({name:"The Dark Knight", genre:"action", year:2008})
    >db.movies.insert({name:"Megamind", genre:"animation", year:2010})
    >db.movies.insert({name:"Paranormal Activity", genre:"horror", year:2009})
    >db.movies.insert({name:"Hangover", genre:"comedy", year:2010})
    
  3. The following command returns all documents from the movies collection:
    >db.movies.find()
    
    

What just happened?

In step 1, we applied the use myfirstdb command to switch to a new database namespace. Any collection/document we create now is going to be stored under this database. Next we create a collection named movies and insert some documents in it:

>db.movies.insert({name:"Source Code",genre:"sci-fi",year:2011})

The db part of the command always refers to the current database, which is "myfirstdb" in this case. The next part is the name of the collection (movies), if it does not already exist in the database, it gets created automatically when you invoke the insert() method on it. The argument to insert is a JSON object, a set of key-value pairs. After invoking the first insert, the database myfirstdb comes into physical existence. You can look into the data directory at this point, where you will find the files myfirstdb.0, myfirstdb.1, and so on that are storing the data for this database.

The find() command, invoked on the collection, returns all the documents in it:

>db.movies.find()
{ "_id" : ObjectId("4db439153ec7b6fd1c9093ec"), "name" : "Source Code", "genre" : "sci-fi", "year" : 2011 }
{ "_id" : ObjectId("4db439df3ec7b6fd1c9093ed"), "name" : "The Dark Knight", "genre" : "action", "year" : 2008 }
{ "_id" : ObjectId("4db439f33ec7b6fd1c9093ee"), "name" : "Megamind", "genre" : "animation", "year" : 2010 }
{ "_id" : ObjectId("4db439f33ec7b6fd1c9093ef"), "name" : "Paranormal Activity", "genre" : "horror", "year" : 2009 }
{ "_id" : ObjectId("4db439f43ec7b6fd1c9093f0"), "name" : "Hangover", "genre" : "comedy", "year" : 2010 }

Pop Quiz - configuring MongoDB

  1. What is the default port address of MongoDB?

    a. 27107

    b. 27017

    c. 27170

  2. How does a new database get created in MongoDB?

    a. By the command create database <databasename>

    b. By the command use <databasename>

    c. By doing use <databasename> first and then doing db.<collectionname>.insert(<jsondocument>)

Installing the PHP driver for MongoDB

To make PHP talk to the MongoDB server, we are going to need the PHP-MongoDB driver. It is a PHP extension library that manages connection to the MongoDB server and enables you to perform all kinds of operations on a database through PHP. Since you are a PHP programmer, I am going to assume you already have a functional PHP environment installed on your machine, running on top of an Apache web server. The driver officially supports PHP versions 5.1, 5.2, and 5.3. So if you are using an older version of PHP, I suggest you upgrade it.

Time for action - installing PHP driver for MongoDB on Windows

Let's try installing the driver on a Windows machine running PHP 5.2 on Apache:

  1. Download the ZIP archive http://downloads.mongodb.org/mongo-latest-php5.2vc6ts.zip on your machine and extract it.
  2. Copy the php_mongo.dll file from the extracted folder to the PHP extension directory; this is usually the folder name ext inside your PHP installation.
  3. Open the php.ini file inside your PHP installation and add the following line:
    extension=php_mongo.dll
    
  4. Save the file and close it. Restart the Apache web server.
  5. Open up your text editor and add the following code to a new file:
    <?php
    phpinfo();
    
  6. Save the file as phpinfo.php inside the DocumentRoot of the Apache web server (the htdocs folder).
  7. Execute the phpinfo.php script in your browser (http://localhost/phpinfo.php). Scroll down to find the section mongo to see all the MongoDB driver-specific information.
    Time for action - installing PHP driver for MongoDB on Windows

Congratulations! You have successfully installed the PHP driver for MongoDB.

What just happened?

In step 1, we download the ZIP file containing the DLL file php_mongo.dll for the PHP-MongoDB driver for PHP 5.2 (for the PHP 5.3 specific version, download http://downloads.mongodb.org/mongo-latest-php5.3vc6ts.zip instead). In step 2, we copy the php_mongo.dll file to the PHP extensions directory. If the installation directory of PHP on your machine is C:\php, the extension directory should be C:\php\ext. Then we edit the php.ini file (located under C:\php as well) to add the line extension=php_mongo.dll to it and restart Apache for the changes to take effect. Next we create and execute a one-line PHP script to invoke the phpinfo() method. If we are able to see the MongoDB driver specific information in the phpinfo() output, listed under section mongo, this means the driver was installed without a glitch.

Note

If you are running PHP on IIS, you should download the thread-safe VC9 version of the driver instead. Get it from the URL http://downloads.mongodb.org/mongo-latest-php5.3vc9ts.zip.

Installing the PHP-MongoDB driver on Unix

In a Unix-based system, the PHP driver for MongoDB can be installed using the pecl (PECL - PHP Extension Community Islam) program. You need to have it installed on your machine, which can be done by using the following command:

sudo pecl install mongo

When the installation is finished, edit the php.ini file (usually found at /etc/php.ini) to add the line:

extension=mongo.so

and then restart Apache.

In case you don't have pecl installed on your machine, you can download the driver source code from GitHub, build it, and install it manually:

$ tar zxvf mongodb-mongdb-php-driver-<commit_id>.tar.gz
$ cd mongodb-mongodb-php-driver-<commit_id>
$ phpize
$ ./configure
$ sudo make install

Check out the Mongo driver installation page http://www.php.net/manual/en/mongo.installation.php on the PHP official website to get operating system specific detailed information.

Connecting to the MongoDB server from PHP

In this section, we will learn how to use the API provided by the PHP-MongoDB driver to create a connection to the Mongo server from a PHP script.

Creating a PHP-Mongo connection

Let's write a very simple PHP program that creates a connection to the MongoDB server and shows all the available databases on that server.

Time for action - creating a connection to the MongoDB server from PHP

  1. Open up your text editor and add the following code in a new file:
    <?php
    try{
    $mongo = new Mongo(); //create a connection to MongoDB
    $databases = $mongo->listDBs(); //List all databases
    echo '<pre>';
    print_r($databases);
    $mongo->close();
    } catch(MongoConnectionException $e) {
    //handle connection error
    die($e->getMessage());
    }
    
  2. Save the file as test_connection.php under the DocumentRoot of your web server.
  3. Open up your browser, and execute the script by going to the location http://localhost/test_connection.php:
    Time for action - creating a connection to the MongoDB server from PHP

What just happened?

We just wrote a simple PHP program to test if the PHP-MongoDB driver we installed works correctly. The program does two simple things. First, it creates a connection to the Mongo server, then it lists all the databases in the server.

Let's examine the code. We created a connection from PHP to MongoDB by instantiating a Mongo object:

try{
$mongo = new Mongo();
……………………………………………………
} catch(MongoConnectionException $e) {
die($e->getMessage());
}

We instantiated the object within a try/catch block to handle the exception named MongoConnectionException in case PHP fails to connect. Once the connection was made, we invoked the listDBs() method on the Mongo object. It returned an associative array, containing three fields. The first field—databases—is an array of associative arrays, each one corresponding to a database in the server, giving us the name of the database, its size in bytes, and a flag specifying if the database is empty or not.

Array
(
[databases] => Array
(
[0] => Array
(
[name] => myfirstdb
[sizeOnDisk] => 67108864
[empty] =>
)
[1] => Array
(
[name] => adming
[sizeOnDisk] => 1
[empty] => 1
)
)
[totalSize] => 67108864
[ok] => 1
)

The totalSize field corresponds to the total size of data in the server (in bytes) and the ok flag specifies if the method ran successfully. Finally, we closed the connection by invoking the close() method on the Mongo object.

Configuring the PHP-MongoDB connection

When no parameter is passed to the constructor of the Mongo class, it connects to the Mongo server running on localhost, on port 27107 (or whatever value is specified for mongo.default_host and mongo.default_port in php.ini). If we want to connect to a server running on a different host and/or port, we can pass the connection string (mongodb://<hostname>:<port_number>) as the $server parameter to the Mongo constructor. For example, to connect to a Mongo server listening on port 8888, we will type the following command:

$mongo = new Mongo($server="mongodb://localhost:8888");

Specifying timeout for the connection attempt

We can specify for how long (in milliseconds) the driver should attempt to connect to the MongoDB server:

try {
$mongo = new Mongo($options=array('timeout'=> 100))
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}

We supplied an array {'timeout' => 100} as the $option argument to the Mongo constructor. In case PHP fails to connect within 100 milliseconds, it will throw an exception named MongoConnectionException.

Have a go hero connect to a MongoDB server on a networked computer

Suppose your computer is connected to a local area network. There is another computer in the network, running on the IP address 192.168.1.101. It is hosting a MongoDB server that is listening on port 8000. Write a PHP script that connects to that MongoDB server, in under one second, and lists all the databases hosted there.

Summary


We covered a lot of things in this chapter.

Specifically, we covered:

  • What the NoSQL movement is

  • What MongoDB is, what is it good for, and who is using it

  • The MongoDB data model (databases, collections, and documents)

  • How to install and run MongoDB on a computer

  • How to create databases, collections, and documents using the mongo interactive shell.

  • How to install the MongoDB-PHP driver on a computer

  • How to create a connection to MongoDB from PHP

We also discussed how to configure the MongoDB server using command-line parameters or configuration files.

By now you should have a PHP-MongoDB development environment up and running on your system. In the next chapter, we will learn to create a simple web application using MongoDB as data backend.

Left arrow icon Right arrow icon

Key benefits

  • Learn to build PHP-powered dynamic web applications using MongoDB as the data backend
  • Handle user sessions, store real-time site analytics, build location-aware web apps, and much more, all using MongoDB and PHP
  • Full of step-by-step instructions and practical examples, along with challenges to test and improve your knowledge

Description

With the rise of Web 2.0, the need for a highly scalable database, capable of storing diverse user-generated content is increasing. MongoDB, an open-source, non-relational database has stepped up to meet this demand and is being used in some of the most popular websites in the world. MongoDB is one of the NoSQL databases which is gaining popularity for developing PHP Web 2.0 applications.PHP and MongoDB Web Development Beginner’s Guide is a fast-paced, hands-on guide to get started with web application development using PHP and MongoDB. The book follows a “Code first, explain later” approach, using practical examples in PHP to demonstrate unique features of MongoDB. It does not overwhelm you with information (or starve you of it), but gives you enough to get a solid practical grasp on the concepts.The book starts by introducing the underlying concepts of MongoDB. Each chapter contains practical examples in PHP that teache specific features of the database.The book teaches you to build a blogging application, handle user sessions and authentication, and perform aggregation with MapReduce. You will learn unique MongoDB features and solve interesting problems like real-time analytics, location-aware web apps etc. You will be guided to use MongoDB alongside MySQL to build a diverse data back-end. With its concise coverage of concepts and numerous practical examples, PHP and MongoDB Web Development Beginner’s Guide is the right choice for the PHP developer to get started with learning MongoDB.

Who is this book for?

This book assumes that you are experienced in web application development using PHP, HTML, and CSS. Having working knowledge of using a relational database system such as MySQL will help you grasp some of the concepts quicker, but it is not strictly mandatory. No prior knowledge of MongoDB is required.

What you will learn

  • Get MongoDB up and running on the machine (Windows/Mac/Linux)
  • Build a PHP-powered website with MongoDB as the data storage
  • Handle HTTP sessions with MongoDB
  • Store website analytics data in real time
  • Process large datasets with MapReduce
  • Use MongoDB to supplement your existing relational database‚Äì build data archives, cache tiers, store results of expensive SQL queries in MongoDB
  • Build location-aware web applications
  • Optimize MongoDB for better performance and security
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 25, 2011
Length: 292 pages
Edition : 1st
Language : English
ISBN-13 : 9781849513623
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Nov 25, 2011
Length: 292 pages
Edition : 1st
Language : English
ISBN-13 : 9781849513623
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 75.98
Instant MongoDB
$26.99
PHP and MongoDB Web Development Beginner's Guide
$48.99
Total $ 75.98 Stars icon

Table of Contents

10 Chapters
Getting Started with MongoDB Chevron down icon Chevron up icon
Building your First MongoDB Powered Web App Chevron down icon Chevron up icon
Building a Session Manager Chevron down icon Chevron up icon
Aggregation Queries Chevron down icon Chevron up icon
Web Analytics using MongoDB Chevron down icon Chevron up icon
Using MongoDB with Relational Databases Chevron down icon Chevron up icon
Handling Large Files with GridFS Chevron down icon Chevron up icon
Building Location-aware Web Applications with MongoDB and PHP Chevron down icon Chevron up icon
Improving Security and Performance Chevron down icon Chevron up icon
Easy MongoDB Administration with RockMongo and phpMoAdmin Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(11 Ratings)
5 star 54.5%
4 star 18.2%
3 star 18.2%
2 star 9.1%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Edgar martinez Dec 12, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
awesome book. I recommend it to anyone coding in php who wants to use mongo and get started right away I was playing with php and mongo in chapter 1. Great book. I loved getting started very quickly. Mongo is very easy and you can rapidly see where the benefits would be 5 star book for sure.
Amazon Verified review Amazon
cedub Feb 17, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I enjoyed reading and building along with the book "PHP and MongoDB Web Development". The book is logically organized and contains many helpful hints and tutorials. I felt the content appropriately addressed the target audience, individuals with some background in web development looking to increase their exposure to a new technology. For me, the best part of the book is the useful examples and exercises, specifically using MongoDB to implement a session manager for clustered web applications, geospacial indexing, and web analytics with asynchronous writes. I found the exercises given in the book to be very relevant to the strengths of MongoDB. Furthermore, the book gives a good introduction to the Map/Reduce concept and provides good examples for those who may not be familiar with it. I thought the author did a nice job of illustrating the fact that while MongoDB has many benefits, it's not the perfect fit for every need. There are even times when it can and should be used with a relational database system and the author gives examples of when this would be an effective use and when it would not. The book provides good resources for those readers wanting to delve a bit deeper into more advanced uses and aspects of MongoDB. Overall, I found "PHP and MongoDB Web Development" to be an excellent reference for building applications with MongoDB. I would, and will, recommend this book to all of my developer colleagues.
Amazon Verified review Amazon
Fran Jan 18, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I learned fast and without problems. Of course Im going to need to read something more, bit the balance between time, effort, money and acknowledge is very positive.
Amazon Verified review Amazon
Joe Feb 29, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I found this book to be very informative for someone who is interested in MongoDB and wants to learn the type of database architecture MongoDB supports. This book has a web-centric view where it shows step-by-step examples that anyone can follow. Every chapter has a review of what is covered in the chapter, and plenty of examples to illustrate the author's points.My take on this subject is from the Database Administrator point of view, and here I found the book to be a little light on substance, but this book is clearly not marketed to that segment but to developers. Some of the advanced topics covered in this book are MapReduce, GridFS and Geospatial location and on these topics this book excels.This book would be a fine addition to any bookshelf and will have a special place in mine. It clearly shows the power of MongoDB and PHP in a Web 2.0 environment and would be a great reference to anyone in Web development.
Amazon Verified review Amazon
Alessandro Pellizzari Jan 08, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Disclaimer: I received the book from Packt Publishing to review it.I tried hard to be objective.General reviewIn a word: excellent. But it can be improved.If I recall correctly, this is the first book about integrating PHP and MongoDB.The writing style is easy and most concepts are clearly explained. Some dark spots remain in the functional programming concepts in the map-reduce dedicated chapter.A deeper explanation could have helped.Every chapter sports various code examples and quizzes scattered through the books help recalling just-read concepts. Maybe they are a little too few.Solutions to the quizzes are in the appendix.Every chapter also has "call to actions" (without solutions, naturally) inviting the users to implement solutions based on explained concepts.My preferred part of the books are the examples: the code is presented full and complete, and only after that, you can read the explanation, with snippets taken from it. You can have a full view of the code and analyse it by yourself, or read the description snippet by snippet.Most other technical manuals split the code, or fill it with comments, making it nearly unreadable.The book style appears to shift a little away from classical technical manual, reminding academic books.Sometimes it seems (often rightly) there is much more behind some functionalities and that the book teaches only the basic usage.In some cases it is clearly written (including a link) that you can deepen your understanding reading online articles.Some minor typos, like array fields defined by : (as in javascript) instead of => in PHP code, or missing quotes in array indexes, are easily spotted and don't lower the quality.Chapter 1: installationAfter a brief introduction to the NoSQL movement explaining its fundamentals,installation on Windows and Linux is described. As for OSX, it simply says "it is just like on Linux".Installation is so easy that it takes at most a couple of pages.Next comes server startup, covering base configuration options, and basic database and collections creation. It ends with PHP driver installation (using PEAR) and a little example script.Chapter 2: first applicationIt became the "hello world" of books covering web techs: you begin building a simple blog, covering insert, delete and alter operations. Then pagination and comments are introduced.It serves its purpouse in introducing CRUD (Create, Read, Update, Delete) operations in MongoDB, covering MongoDB query language, including limit, skip, cursors and safe writing concepts.The chapter ends with some peculiar operations (upserts, field increment, field removal) and the distinction between embedded and referenced document, also explaining how to do a "select" operation on embedded documents.Chapter 3: a session managerAfter a brief introduction, the book delves into creating a custom session handler.A (singleton) class is introduced to manage the connection to the DB, and it will be used throughout the entire book. A class is defined to handle the PHP session using a MongoDB collection. This can easily be reused in own projects, being nearly completely transparent.The chapter ends with a user login/logout example.It is useful to understand how to abstract access to MongoDB through a class, how to use upsert and also to know how to use a generic (even SQL) database to handle sessions.Chapters 4 and 5: aggregation and statisticsI cover the two chapters together because they deal with the same topics: map-reduce and group().Map-reduce is maybe the hardest topic for thos used to procedural or OOP languages, as it embraces function programming concepts. On the other hand, group() is similar to the SQL GROUP BY concept.These chapters' arguments are not easy to grasp, and I would have liked more examples. Luckily the given examples are very practical (tag cloud, web access statistics, ...) and not abstract aggregations.Capped collections are introduced here.Chapter 6: RDBMS integrationThis is maybe the least useful chapter, in my opinion, but it could be important to others. Several examples of how to connect to a SQL (MySQL) DB and MongoDB in parallel: how to use MongoDB as a query cache, or to archive old data, so to remove burden from MySQL queries.Chapter 7: GridFSThis chapter is a little thin, given the topic, but it gives you everything you need to start working with GridFS to store (binary) files in the database.MongoDB excels in its simplicity, and the examples are short and clear.One of the "call to actions" asks to implement a thumbnail gallery, saving the thumbnail along with the original image, but does not explain if you can save different files in the same document (hint: you can't).Chapter 8: geolocationThis chapter introduces MongoDB's geolocation features: 2D indexes and server-predefined procedures to search distance-based data.A good introduction, even if it leaves some itches to scratch about measure units (degrees? radians? meters?).Excellent explanation on how to use the data with Google Maps to visualize the results.Chapter 9: securityThe chapter with fewer PHP code lines in it, focuses on console administration for user (and password) access management.It also covers indexes creation and analysis: this part should have been introduced earlier in the book.Chapter 10: RockMongo and phpMoAdminA quick introduction to two web-based (PHP) interfaces for administration query and, above all, backup and restore of databases and collections.Covers pros and cons of both solutions, as well as installation and basic use.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon