November 23, 2014
Hot Topics:

MongoDB Delivers NoSQL Flexibility and Scalability to Developers

  • June 16, 2010
  • By Jason Gilmore
  • Send Email »
  • More Articles »

Using MongoDB with PHP

MongoDB drivers are available for most of the popular programming languages, among them PHP, Python, and Ruby.

Configuring MongoDB for PHP is particularly easy, just install PHP's MongoDB driver:

%>sudo pecl install mongodb


Then open your php.ini file and add the following line, restarting Apache after you save the file:

extension=mongo.so


When configured, you can create a script that queries the previously created library database:

<?php $m = new Mongo(); // Connect to a database $db = $m->library; 
// get the database named "foo"
// Retrieve the collection $books = $db->books;
// Find a book $book = $books->findOne(array('author' => 'Dashiell Hammett'));
// Output the title echo $book['title']; ?>


You can iterate over all books using the find() method and a looping mechanism:

// Retrieve the collection $books = $db->books->find(); while( $books->hasNext() ) 
{ $book = $books->getNext(); echo "{$book['title']}<br />"; }


Inserting new books is also quite easy, accomplished using the insert() method:

$books->insert(array('title' => 'The Sun Also Rises', 
'author' => 'Ernest Hemingway'));


For more information about using PHP with MongoDB, see the MongoDB documentation, which among other things provides links to quite a few community tools and plugins. Also, if you're interested in using MongoDB in conjunction with Rails, be sure to check out the Developer.com article, A Rails Cloud Implementation Using MongoDB and Heroku.

Conclusion

NoSQL databases such as MongoDB are being adopted within enterprises large and small due to their flexibility and scalability, two traits which are music to most developers' ears. Are you using MongoDB or a similar solution? If so, tell us about your experience in the comments!

About the Author

Jason Gilmore is the founder of EasyPHPWebsites.com. He also is the author of several popular books, including "Easy PHP Websites with the Zend Framework," "Easy PayPal with PHP," and "Beginning PHP and MySQL, Third Edition."


Tags: NoSQL, MongoDB



Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel