MongoDB Tutorial sample PHP application

On a wampserver, Install the php_mongo-1.3.1 extension and you will be able to connect to mongo. you can refer here to mongo installation.

You must verify after restarting apache that mongo is activated and of course look Compiler Version for dlls (VC9 or VC6) if VC9 you must use this dll : mongo-latest-php5.3vc9ts

mongo001mongo002

A sample php script to test with this dll is below

<?php
try {
// connect
$m = new MongoClient();

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($document);

// add another record, with a different "shape"
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
// disconnect from server
$m->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server');
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
?>

THE OUTPUT WILL BE :

mongo003

 

Another sample will be this script :

selectDB('myDb');

// Sélection d'une collection. Si elle n'existe pas, elle est créée
$people = $db->selectCollection('people');

// On insère un premier enregistrement
$people->insert(
    array(
        'firstname' => 'John',
        'lastname' => 'Doe',
        'email' => 'john.doe@somewhere.com'
    )
);

// On insère un second enregistrement. Notez que les colonnes sont différentes.
$people->insert(
    array(
        'firstname' => 'Jane',
        'lastname' => 'Doe',
        'mobile' => '06.01.02.03.04'
    )
);



// On retrouve et on affiche tous les éléments de la collection
$docs = $people->find();
foreach($docs as $doc) {
    var_dump($doc);
    echo '
'; } // On retrouve Jane par son prénom $jane = $people->findOne(array('firstname' => 'Jane')); var_dump($jane); echo '
'; // disconnect from server $connection->close(); } catch (MongoConnectionException $e) { die('Error connecting to MongoDB server'); } catch (MongoException $e) { die('Error: ' . $e->getMessage()); } ?>

THE OUTPUT WILL BE :
mongo004

Cheers,

extradrmtech

Since 30 years I work on Database Architecture and data migration protocols. I am also a consultant in Web content management solutions and medias protecting solutions. I am experienced web-developer with over 10 years developing PHP/MySQL, C#, VB.Net applications ranging from simple web sites to extensive web-based business applications. Besides my work, I like to work freelance only on some wordpress projects because it is relaxing and delightful CMS for me. When not working, I like to dance salsa and swing and to have fun with my little family.

You may also like...