How do I connect PHP to MongoDB

MongoDB is a widely used NoSQL database, implemented based on the document-oriented model and intended for storing semi-structured data. The guide below provides an instruction on how we can easily use it in a bundle with the PHP app, hosted within the Cloudjiffy Cloud.

Create an Environment

Enter the email address within the one-click installation widget below to get an environment with the MongoDB server created, in just a few clicks:
or perform this manually using the following instruction:

Log into the Cloudjiffy account and create a new environment with the MongoDB node of the preferred version (can be found within the NoSQL wizard section).

              

Add all the rest of the necessary instances (if there are any - we’ll also include Apache to subsequently deploy a test app to it; however, it could be located in a separate environment as well) and configure other required parameters, like amount of resources, region, environment name, etc.

Click the Create button when ready and wait for a couple of minutes for the environment to be set up.

MongoDB Configurations

1. Enter the email box and find a letter from Robot@Cloudjiffy, which contains the MongoDB instance details and access data:

                                   

2. Here, click on the Access URL link or switch to the dashboard and Open in browser the MongoDBnode.

                                                    

In the opened browser tab, I’ll see the Sign in form for the MongoDB admin panel. Enter the admin credentials I’ve received within the abovementioned email and click Login to access it.

3. Now, let’s create a separate database to establish the connection to. For that, switch to the Databases tab and specify a Name for it within the Create Database section (for example, mongodb-connect).

      

Click Save to proceed.

4. The next step is to create a separate DB user for working with our newly added database. Thus, switch to the Execute tab and paste the following command inside the shown input field:

db.createUser({ user: "user_name", pwd: "password", roles:[{ role: "readWrite", db: "db_name"}]})

where

  • user_name - name for the new DB user
  • password -  password for this user
  • db_name - database (the above created one is suggested) this user will have the read/writepermissions for

Then, select the corresponding database using the drop-down list below and Execute the specified command with the same-named button. I’ll get the success response in just a few seconds.

5. Now the need to activate the dedicated connection driver for enabling the interaction between the app server and MongoDB. At Cloudjiffy, it is included to all PHP app servers’ builds by default.

Note that starting with the 4.3 Cloudjiffy version, there are two driver versions available at all of the newly created PHP app servers:
  • mongo.so (currently, it’s considered deprecated)
  • mongodb.so

Both these extensions implement different API, so we recommend to use the legacy module for keeping old applications running, whilst adapt the new projects due to the latest one.

Tip: The current version of used Cloudjiffy installation usually can be seen within the logo in the top left dashboard corner. Additionally, I can check it within the Cloudjiffy Cloud Union Catalog.

             

So, in order to enable the required driver, return to the dashboard, hover over the compute node in the environment and click on the appeared Config button.

6. Within the opened configuration manager tab, expand the etc folder and choose the php.ini file inside.

   

Scroll down to the approximately 483rd line and uncomment the string with the required driver (either mongo.so or mongodb.so extension) by removing the semicolons mark at its beginning.

7. Save the performed changes and Restart the app server node to apply them.

  

Application Deployment

Now I can proceed to application deployment into the environment I’ve just prepared - either using the Cloudjiffy Deployment Manager (for projects, packed into a single archive) or fetching it directly from a GIT/SVN repo.

As an example, we’ll use the following simple app, designed to verify the establishment of connection between the corresponding compute node and the specified MongoDB server by means of the latter mongodb.so extension.

index.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
   
 
   
 

Test MongoDB Connection

 
"#" name="form" method="POST">
  "10">
    
      
    
    
    
    
  
Host "text" name="host" value="" size="40">
User "text" name="username" value="" size="20">
Password "text" name="password" value="" size="20">
Database "text" name="database" value="" size="20">
  "submit" name="sub" value="Test Me!">
   
if (@$_POST['sub']){
 $host=$_POST['host'];
 $username=$_POST['username'];
 $password=$_POST['password'];
 $userdb=$_POST['database'];
 $database=$userdb.".phptest";
   
  try{
    $manager = new MongoDB\Driver\Manager("mongodb://{$host}/{$userdb}", array("username" => $username, "password" => $password));
       if ($manager) {
        $bulk = new MongoDB\Driver\BulkWrite;
        $bulk->insert(['x' => 1]);
        $bulk->insert(['x' => 2]);
        $bulk->insert(['x' => 3]);
        $manager->executeBulkWrite($database, $bulk);
   
        $filter = ['x' => ['$gt' => 1]];
        $options = [
            'projection' => ['_id' => 0],
            'sort' => ['x' => -1],
        ];
 
        $query = new MongoDB\Driver\Query($filter, $options);
        $cursor = $manager->executeQuery($database, $query);
            }  
  }catch(Exception $e){
    echo  "

Doesn't work

";
    print_r($e);
        exit;
  }
 
if ($host)
 echo "

Good connection

";
 
?>
   

Thus, if I’d like to test the connection itself, just download the already wrapped package with the project, shown above, and deploy it.

Tip: For the legacy driver version (i.e. mongo.so), please use this test application. The workflow will be similar to the described below.

Consequently, I’ll receive an environment, similar to the one shown above.

Connection Check Up

1. Open the environment in Browser with the same-named button - I’ll see a simple form for entering the MongoDB database details.

< im10 >

The following values should be specified:

  • Host - link to the database admin panel without the https:// part (can be found within the corresponding email or just copied from the browser address bar after clicking Open in browser for the MongoDB node)
  • User - name of the user I’ve assigned to the database (dbuser in our case)
  • Password - password for the user, specified within the previous field
  • Database - name of the required database (mongodb-connect in our case)

After the data is entered to the corresponding fields, click on the Test Me! button.

2. If the specified information is correct, the Good connection message will be shown.

< im 11 >

Otherwise, I’ll get a notification that connection Doesn’t work and the detailed output of the error this was caused by.

3. In addition, upon a successful connection establishment, the new phptest collection with a few new records inside will be added to the specified database.  

< im12 >

Thus, I can navigate to the DB’s admin panel for making sure everything works correctly and proceed with performing any other required operations.


Was this article helpful?

mood_bad Dislike 0
mood Like 0
visibility Views: 17195