PHP & MongoDB - Environment Setup



Install MongoDB database

Follow the MongoDB installation steps using MongoDB - Environment Setup

Install PHP

Follow the PHP installation steps using PHP - Installation

PHP MongoDB Driver Installation

Before you start using MongoDB in your PHP programs, you need to make sure that you have MongoDB Extension and Mongo Driver and PHP set up on the machine. You can check PHP - Installation for PHP installation on your machine. Now, let us check how to set up MongoDB CLIENT.

Install PIE and Composer

Install MongoDB Extension

We need to install PIE as pie.phar from https://github.com/php/pie/releases in order to install mongodb extensions in PHP.

Run the following command to install mongodb extensions.

php pie.phar install mongodb/mongodb-extension

Manually, we've downloaded php_mongodb-2.1.4-8.5-ts-vs17-x86_64.zip and extracted php_mongodb-2.1.4-8.5-ts-vs17-x86_64.dll, renamed to php_mongodb.dll and placed under ext directory.

php.ini is modified to have mongodb extension.

extension=php_mongodb.dll

Install MongoDB Driver for PHP

Create a PHP project and run the following command to configure mongodb dependencies.

composer require mongodb/mongodb

Composer will manage all dependencies and create a autoload.php file under vendor sub folder.

Connect to Database

To connect database, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically.

Following is the code snippet to connect to the database −

<?php
   require __DIR__ . '\vendor\autoload.php';
   try {
	  $uri = "mongodb://localhost:27017";
      // connect to mongodb
      $client = new MongoDB\Client($uri);
      echo "Connection to database successful.";
       // select a database
      $db = $client->mydb;
      echo "Database mydb selected.";
   } catch (MongoDB\Driver\Exception\Exception $e) {	   
      echo "Exception:", $e->getMessage(), "\n";
   }
?>

Output

Now, let's compile and run the above program to create our database myDb.

On executing, the above program gives you the following output.

Database mydb selected
Advertisements