Web Programming TutorialsLearn How to Integrate MongoDB and PHP

Learn How to Integrate MongoDB and PHP

PHP is the most used programming language for the web today. PHP is not just suitable to build Web Applications, you can also build powerful REST APIs with it. PHP is very easy to learn and implement and is well supported throughout the world.

PHP has been supporting traditional SQL databases notably MySql very well. MySql is the most used open source database in the world. The combination of PHP and MySql has been a dominating combination for many years.

Apart from supporting SQL databases, PHP has been able to keep up with the recent advent of NoSql databases. MongoDB being the most popular NoSql database, is well supported with PHP. PHP comes with the MongoDB extension and many libraries to make a job easier for the programmer. However, the most popular MongoDB library for PHP is the official package accessible at https://docs.mongodb.com/php-library/current/.

This particular library makes using MongoDB very easy with PHP. In this article, we will cover basic operations covered by this library that makes a developer’s job easier.

Installing MongoDB with PHP

You can either download this library directly or you can install it very easily using Composer. If you are using composer, you can download this library using the following command:

<code>$ composer require mongodb/mongodb:"=1.0.5"</code>

We are installing MongoDB library version 1.0.5. You need to have MongoDB extensions installed as well. For this example, we are using PHP version 7.0.25. If you don’t have MongoDB extension installed, you can simply install it using the following command on Ubuntu 16.04:

<code>$ apt-get install php-mongodb</code>

Code Samples
Make sure that you have MongoDB installed and running before proceeding with the code samples below.

First things first, make sure that you have your Composer’s autoload.php file included in your code file as follows:

<code>
# initializing
require 'vendor/autoload.php'; # include the SDK using the Composer autoloader
</code>

Now, we’ll start and initialize our collection for this example:

<code>
# initializing collection
$collection = (new MongoDB\Client)->comicverse->superheroes;
</code>

‘comicverse’ is our database, ‘superheroes’ is our collection. Basically, there is no special command for creating a database and a collection. MongoDB autocreates these if not found.

Create a document
Now, the first task that we’ll do is create our document which is as follows:

<code>
# create a document
$insert_ironman_document = $collection->insertOne([
    "real_name" => "Anthony Stark",
    "alias" => "Tony",
    "weapons" => [
   	 "Repulsors",
   	 "Missiles",
   	 "Unibeam",
   	 "Lasers",
   	 "Shoulder mounted Guns",
   	 "Flares"
    ],
    "abilities" => [
   	 "Nuclear Powered Energy Core, known as 'Arc Reactor'",
   	 "AI Armored Suit",
   	 "Super Strength",
   	 "Flight",
   	 "Diving",
   	 "Space Travel"
    ],
    "love_interest" => "Virginia 'Pepper' Potts"
]);
printf("Inserted ID for Ironman record is: %s\n", $insert_ironman_document->getInsertedId());
</code>

Make sure that the above command is only executed once, as executing the above command more than once will create duplicate records with the same data but different IDs. You might not want that to happen.

Print all documents
If you want to print all documents created under a particular collection, you can use the following code snippet. The function ‘$collection->find()’ returns a pointer, using which we can iterate over all the found records. You can also specify search criteria (as a PHP array) in this function as a parameter to the ‘find()’ function, which will be covered later.

<code>
# print down all documents
foreach($collection->find() as $document){
    print_r($document);
}
</code>

Updating records
MongoDB comes with various functions to update records in a collection. Here, we will cover the ‘updateOne()’ function:

<code>
# updating our record
$our_record_to_update = $collection->findOne(["alias" => "Tony"]);
if(!is_null($our_record_to_update)){ # we found our record, let us proceed with updation
    $update_result = $collection->updateOne(
   	 ['alias' => 'Tony'],
   	 ['$set' => ['alias' => 'Machinist']]
    );
    print_r($update_result);
}
</code>

In the above code, our function ‘updateOne()’ accepts two parameters, the first one is the search criteria and the second parameter is the value which we want to replace. We will first check whether or not the record/document exists before proceeding with the updation.

Delete all records

This is just a one liner, All you have to do is execute the following code snippet:

<code>
# delete all records from a collection
$collection->drop();
</code>

Conclusion: –
Of course, this library comes with much more functionality. You can find all information on this library over here. MongoDB is easy to use as compared to the other databases. This library makes process even easier working with MongoDB. Sample code prepared in this article has been attached to this article.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -