bhavish030
bhavish030

Reputation: 53

MongoDB and PHP connection

I am trying to use MongoDB with php5.6 on Ubuntu 16.04. I have a php script that creates a collection. When i open the script on my Apache Web server, it says "connection successful, collection created" but when i login in the mongo terminal and switch to the database(ecoss), i can't find the collection.

To make the connection: i installed the mongoDB extension by running sudo apt-get update and sudo apt-get install php5.6-mongo

Afterwards i edited my php.ini file and added the extension extension=mongo.so;

Installation of php-mongo:

enter image description here

Extract of my php.ini file:

enter image description here

Here is my php script create.php

<?php

    // connect to mongodb
    $m = new MongoClient();

    $db = $m->ecoss;    
    echo "Connection successful, Database ecoss selected" . "<br>";

    $collection = $db->createCollection("mycol");
    echo "Collection created succsessfully";

?>

After executing the above script, output on my browser:

enter image description here

Output on mongo terminal after connecting to ecoss database and running the command show collections :

enter image description here

Upvotes: 1

Views: 569

Answers (1)

bhavish030
bhavish030

Reputation: 53

My problem has been solved!

When creating a new collection through php, the collection will be created. Thanks to @eselskas i saw that when dumping $collection, it returned ecoss.mycol. The problem is that the collection won't appear on mongo shell after connecting to the database ecoss and running the command show collections. This is due to authentication problems with php accessing mongo.

Below are the steps that helped me to solve this problem:

  1. Connect to admin database with use admin
  2. Drop the admin database db.dropDatabase()
  3. Remove --auth in the file mongod.service sudo nano /lib/systemd/system/mongod.service. The line ExecStart should appear as ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (after removing --auth)
  4. Run the command sudo systemctl daemon-reload and sudo systemctl restart mongod to reload the service.

After the above steps, i run my create.php script, and logged in mongo and my database ecoss then made show collections, i could clearly see my collection mycol.

Upvotes: 1

Related Questions