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
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 :
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()); } ?>
Cheers,