Hello again,

Another challenge that I came over was to connect my PHP installation 5.5 with a MongoDB 3.2.

The mongodb-php-library isn’t well documented in my opinion. They don’t tell you how to do it or where to get the dll extension and what you need to do.

This is the new driver (mongodb) or php library as they call it. The old one is mongo, look this it doesn’t have the db in the end.

First of all you need to download and install composer. During the installation you will have to point to your php installation, if it doesn’t locate it by itself.

Then you need to download the mongodb extension which is appropriate for your version. Note, in order to get the correct file you need to press the DLL next to the windows logo. After that you will need to choose your php version, architecture 32 vs 64 bit and thread safe or not libraries. I would suggest to get the thread safe. In my case I got the version 1.1.1 => php 5.5, 32 bit and thread safe.

Next thing to do is to go to your php folder. You will need to copy your dll file to <path-to-php>/ext and edit <path-to-php>/php.ini and add the following line:

extension=php_mongodb.dll

Restart your Apache server and go to the folder/project that you need to install the mongo driver, i.e. htdocs/mongoTest.

Open a command prompt there, a simple way is to right to do that is to right click on the folder that you want to open it while pressing shift, you shouldn’t have selected any files when you press the right click, and then would be a hidden option that will show <open command window here> and will open a cmd at that path 😀

Type:

> composer require "mongodb/mongodb=^1.0.0@beta"

This will make composer to download this library, mongodb, and the current folder. Notice that a new composer.json file was creating, which contains all the libraries and other restrictions in order to make your project run, for example mongodb lib and php >= 5.5.

To test that everything is set up correctly, make a new php file with the following code and replace your values, host/port, dbname and collection

<?php

//This line is to include the dependencies 
require 'vendor/autoload.php';

$serverName = "localhost";
$port = 12345;
$manager = new MongoDB\Driver\Manager("mongodb://$serverName:$port");
$collection = new MongoDB\Collection($manager, "database.someCollection");

//get all items
$result = $collection->find();

foreach ($result as $entry) {
    //print element _id and time
    echo $entry->_id, ': ', $entry->time, "</br>";
}


echo "IT works!";

Run it and if you have done everything correct it will work!

The way to access your values in the this driver is to directly access the $result-> members!

 

 

Cheers!

Advertisements