MongoDB banner

I have no experience with NoSQL databases and was curious to learn a bit more, with the goal of using MongoDB on a Heroku project. Here is a brief outline of my experiment with PHP and MongoDB on my dev machine:

In this post:

  1. Setting up MongoDB
  2. Configuring MongoDB
  3. Configuring PHP
  4. Writing your app

1. Setting up MongoDB

Download and install MongoDB. Add it to your environment path; something like: C:\Program Files\MongoDB\Server\3.0\bin

2. Configuring MongoDB

MongoDB must actually be running on your PC. Open up a command window / Powershell and simply type mongod

Here is a great tutorial:

3. Configuring PHP

Download the PHP/MongoDB dll — I downloaded the threadsafe one

In your php.ini, add: extension=php_mongo.dll

Restart Apache

4. Writing you app

I used the following tutorial to write my first PHP / MongoDB script:

This is my little PHP / MongoDB app. Remember that everything kinda happens on the fly. This feels very odd at first if like me you are used to spending time in setting up your MySQL tables before you even start coding your app. I soon found it to be quite liberating:

echo '<!DOCTYPE html>';
echo '<html lang="en">';
echo '<head>';
	echo '<meta charset="utf-8">';
	echo '<title>Hello World &mdash; PHP &amp; MongoDB</title>';
	echo '<!--[if IE]>';
		echo '<script src=""></script>';
	echo '<![endif]-->';
echo '<style>';
echo '* {font-family: Arial;}';
echo '</style>';
echo '</head>';
echo '<body>';

echo '<h1>Hello World</h1>';
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
echo '<fieldset>';
echo '<p><label>First Name </label><input type="text" name="first_name" placeholder="First Name" /></p>';
echo '<p><label>Last Name </label><input type="text" name="last_name" placeholder="Last Name" /></p>';
echo '<p><label>Tags </label><input type="text" name="tags" placeholder="Comma separated list of tags" /></p>';
echo '</fieldset>';
echo '<input type="submit" name="submit" value="Add" />';
echo '</form>';

// Configuration
$dbhost = 'localhost';
$dbname = 'test';

// Connect to test database
$m = new Mongo("mongodb://$dbhost");
$db = $m->$dbname;

// Get the users collection
$c_users = $db->users;

	if($_POST) {
		$since = date("Y-m-d H:i:s");
		$first_name = $_POST['first_name'];
		$last_name = $_POST['last_name'];
		$tagsArr = explode(",",$_POST['tags']);
		$user = array(
			'first_name' => $first_name,
			'last_name' => $last_name,
			'member_since' => $since,
			'tags' => array($tagsArr)

		// Insert this new document into the users collection

	// get the collection
	$user = $c_users->find();
	foreach ( $user as $id => $value ) {
		echo $id;
		echo '<pre>';
		var_dump( $value );
		echo '</pre>';
		echo '<hr />';

echo '</body>';
echo '</html>';

By foxbeefly

PHP / MySQL Developer. HTML, CSS and some JavaScript.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.