How to setup PHP App With MongoDB

24 de octubre, 2017 @ 13:37 — 0 comentarios

This tutorial has been created having in mind, it's going to be used with guebs.eu services, but may be also valid for general purpose.

1.- Include MongoDB extension to your PHP setup

Here in guebs.eu the MongoDB extension is available starting on PHP 5.6. To enable the extension you need to access PHP Configuration:

How to modify PHP configuration

The new parameter in the configuration, should be as follow:

New parameter: extension = mongodb.so

Remember to push Save button.

 

Once this has been done, you can now check the extension is activated throught the phpinfo() function on a test file, it should be something like this:

2.- Use the Oficial MongoDB PHP Library

You can adquire this library, using composer command, wich is availabe on all our servers at guebs.eu. The oficial documentation can be seen in this websites:

 

Remember you need to access to your hosting server using SSH service:

How to access your hosting via SSH

 

Once loged in, you may do something like this:

cd public_html
/opt/php7.0/bin/php -dextension=mongodb.so /opt/cpanel/composer/bin/composer require mongodb/mongodb

 

3.- MongoDB PHP example

<?php

require 'vendor/autoload.php' ;

#change conection data

$uri="mongodb://user:password@host/database?ssl=false";

$client=new MongoDB\Client($uri);

$collection = $client-&gt;base_de_datos-&gt;productos;

$result = $collection-&gt;insertOne( [ 'item' =&gt; 'producto1', 'cantidad' =&gt; '200' ] );

echo "Inserted with Object ID '{$result-&gt;getInsertedId()}'";

?>

Check the oficial documentation for further information:

  • http://php.net/manual/es/mongodb.tutorial.library.php
  • https://github.com/mongodb/mongo-php-library
  • https://docs.mongodb.com/php-library/master/