By Ran Bar-Zik | 3/16/2018 | General |Beginners

Using MongoDB in PHP

Using MongoDB in PHP

In our previous MongoDB articles, we talked about import and export. In all the previous articles until now, we’ve been agnostic—we’ve only run MongoDB straight from the console. But in the real world we need to use some kind of programming language to run the database, and it doesn’t matter if it’s PHP, Java, Node.js, or any other language. At the end of the day we’re going to be using some kind of abstraction layer.

 

So why learn MongoDB on its own at all? For a few reasons: any abstraction layer requires us to know the syntax of the commands, no abstraction layer will save us if we need to design our own database, and at some point, something is bound to go wrong and we’re going to have to investigate via the console. Also, with MySQL or even WordPress for that matter, where there’s the abstraction layer of WordPress on top of the abstraction of PHP/MySQL, there have been many times where I’ve had to test the queries in the MySQL console when things went awry.

 

But, after investing time and learning so much, we also need to talk about MongoDB’s abstraction. So if you’re here but haven’t been through the previous articles, or let’s say you’re still unsure of concepts like CRUD, I would recommend that you at least learn the basics before continuing.

 

Now to the matter at hand. Working with PHP in MongoDB is particularly easy. To do this we need to use the MongoDB Class.

 

The Mongo Extension that we need to use to be able to work with MongoDB in PHP does not come by default with PHP—we have to install it. Here’s how to do so in Linux:

 

First off, we need to make sure we have the php5-dev package. If you don’t have it, install like so:

apt-get install php5-dev

This package simply allows PHP to be recompiled with new modules. Once it’s installed we can continue with the installation. Detailed installation instructions can be found in the PHP documentation. I’m just copying from php.net the instruction for Ubuntu (and other Debians).

sudo pecl install mongo

After this, you’ll need to put this line in php.ini, under Dynamic Extensions:

extension=mongo.so

And don’t forget to restart Apache with:

sudo /etc/init.d/apache2 restart

How do we know if it’s installed? Just use the php_info command to see all the modules that are installed. If everything is OK, you’ll see “mongo”, including the details. You can also use this:

print extension_loaded("mongo") ? "Loaded\n" : "Not Loaded\n";

You can of course install the Mongo Extension for PHP in Windows. But god help you if you try. Such abominations will not be discussed here. Either way, the link above also has an explanation for installing in Windows. I’d rather be hit by a bus, but ya know, it that’s your thing then go for it.

 

The documentation for the class is quite good and you could really just look there, but I’ll write a little about the feature here.

 

In order to connect to a database (or use it), we need to create an instance of the class like so:

$m = new Mongo(); 

If MongoDB is on a remote server, or you have heightened security, you’ll have to pass arguments to the constructor. If you installed MongoDB according to my previous guide then you don’t need to pass an argument. Just that one line and you’re good to go.

 

I’m going to assume that you have the collection of 100 users that we’ve in past articles. If not, you can create it by copying and pasting the following code in to the Mongo console:

function randomString() {
   var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
   var randomstring = '';
   var string_length = 100 + Math.floor(Math.random() * 200);
   for (var i = 0; i < string_length; i++) {
       var rnum = Math.floor(Math.random() * chars.length);
       randomstring += chars.substring(rnum, rnum + 1);
   }
   return randomstring;
}
for (var i = 0; i < 100; i++) {
   db.clients.insert({
       x: i,
       name: randomString(),
       value: _rand() * 100
   });
}

Now, after all the preparations and installations, the time has come to write a little PHP. All the examples here are based on the very nice guide provided by PHP.

 

In order to create a basic query, all we have to do is run use test (which is our database) and then the simple find query. Here’s an example:

<?php 
try 
{
   $m = new Mongo(); // connect
   $db = $m->selectDB("test");
   $collection = $db->users;
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $document) {
   echo $document["name"] . "\n";
}

}
catch ( MongoConnectionException $e ) 
{
   echo '<p>Couldn\'t connect to mongodb, is the "mongo" process running?</p>';
   exit();
}

Notice that the code is wrapped in a try-catch. I normally don’t like to complicate the code in these guides, but this time I used it. Just read what’s in the try if you’re not clear about it.

 

First there is a connection to MongoDB. In this case I didn’t pass any arguments with the connection since everything is on my local environment. If you installed MongoDB according to the first article of this series, then you don’t need to pass anything either. Either way, these arguments aren't particularly complicated. After, I chose the database, like with use db. Then I isolate the collection from the database and run the find query on it—for now with no parameters.

 

The interesting part of the code is:

$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $document) {
   echo $document["name"] . "\n";
}

The cursor is more or less my pointer. Just like in any other database, the queries come as an object to which we need to iterate over, with the pointer/cursor passing from one document to the next.

 

If we want to put a parameter in find (and we always need to), it works like this:

<?php 
try 
{
   $m = new Mongo(); // connect
   $db = $m->selectDB("test");
   $collection = $db->users;

   $query = array( 'x' => 18 );

$cursor = $collection->find($query);

// iterate through the results
foreach ($cursor as $document) {
   echo $document["name"] . "\n";
}

}
catch ( MongoConnectionException $e ) 
{
   echo '<p>Couldn\'t connect to mongodb, is the "mongo" process running?</p>';
   exit();
}

I’m passing a query that’s basically an array. In this case the query requests users whose x is equal to 18. It’s like:

db.users.find({"x":18})

And if we want to write a query that uses additional parameters? Like $gt? Or like all those greater than 18? Then the query would look like this:

$query = array( 'x' => array( '$gt' => 18 )  );

If we want to combine a few conditions (for instance to find something in a specific range) then we can use:

$query = array( 'x' => array( '$gt' => 20, "\$lte" => 30 )  );

With more complicate conditions we can simply add members to the array:

<?php 
try 
{
   $m = new Mongo(); // connect
   $db = $m->selectDB("test");
   $collection = $db->users;

   $doc = array(
   "name" => "Ran",
   "x" => 9999
);

$collection->insert( $doc );

}
catch ( MongoConnectionException $e ) 
{
   echo '<p>Couldn\'t connect to mongodb, is the "mongo" process running?</p>';
   exit();
}

First we create the document, then we put it in.

 

There are lots more examples at php.net. And each operation that we’ve learned so far—data retrieval, delete, update, and even adding indexes—we can reproduce in the PHP abstraction.

 

Next time, we’ll look at MongoDB with Node.js.

 

Previous article: Import and Export

 Next article: Using MongoDB with Node.js

 

About the author: Ran Bar-Zik is an experienced web developer whose personal blog, Internet Israel, features articles and guides on Node.js, MongoDB, Git, SASS, jQuery, HTML 5, MySQL, and more. Translation of the original article by Aaron Raizen.

By Ran Bar-Zik | 3/16/2018 | General

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
1490
Ronan McCarthy
Cross-Platform & Web developer.
Web | Mobile and 6 more
View Profile
User photo
1230
Gary Green
Expert programmer, Ask what you want
Web | JavaScript and 3 more
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now