Cloud Zone is brought to you in partnership with:

After teaching math (and a little computer science) for 14 years, Brian changed careers in 2006 with the idea that getting out of his comfort zone would be good. So now he works as a writer and programmer at Microsoft who specializes in PHP and Windows Azure. Brian is a DZone MVB and is not an employee of DZone and has posted 82 posts at DZone. You can read more from them at their website. View Full User Profile

How to use MongoDB from PHP in Windows Azure Web Sites

11.04.2012
| 2927 views |
  • submit to reddit

 

Earlier today, MongoLab announced the availability of MongoDB as a service on Windows Azure: MongoLab on Windows Azure. From my point of view this is great as it now makes it easy to use 3 of my favorite technologies in concert: Windows Azure Web Sites, PHP, and MongoDB. So, I’m wasting no time in playing with them: this post will show you how to create a MongoDB database and access it from PHP in Windows Azure Web Sites.

Note: I strongly encourage you to read MongoLab’s announcement before following this tutorial as it contains information about the beta status of MongoLab’s offering.

I’m assuming you have a Windows Azure account. If you don’t, you can sign up for the free trial.

Create a MongoDB database

To create a MongoDB database…

1. Log in to the Windows Azure portal, click +NEW at the bottom of the page, then select STORE.

GoToStore

2. Scroll through the available add-ons, select MongoLab, and click the arrow at the bottom of the screen.

SelectMongoLab

3. Provide the MongoDB database name and select the region for deployment. Click the right arrow at the bottom of the screen.

Note: The name you provide here will be the name of your database, and in the free offering (which is all that is available now), you only get one database.

ProvideName

4. Confirm your “purchase” (it’s free!).

Purchase

5. After your database has been created, you will be able to see it in the portal under ADD-ONS. Click on the name of the database to go to its dashboard.

portalshot

6. Explore the links in the dashboard, but to get connection information, go to the next step.

dashboard

7. Click CONNECTION INFO to get your MongoDB connection string. Make note of the connection string as you will need it later. (Also note that by clicking MANAGE, you will be taken to MongoLab’s web UI for managing your database.)

connectionInfo

That’s it. Your MongoDB database is now ready to use.

Create a Web Site and enable php_mongo.dll

Once you have a MongoDB database set up, you can connect to it from anywhere by using the connection string you noted in the section above. If you want to connect to it from a site in Windows Azure Web Sites, however, you’ll need to a little bit of extra work to enable the MongoDB extension:

  1. Download the php_mongo.dll extension here: https://github.com/mongodb/mongo-php-driver/downloads. Choose the download for PHP 5.3, Windows, VC9. After you have downloaded the archive, select the appropriate non-thread-safe version from the available files (e.g. php_mongo-1.2.12-5.3-vc9-nts.dll).
  2. Follow instructions in this post for enabling the MongoDB extension in Windows Azure Web Sites: Using Custom PHP Extensions in Windows Azure Web Sites. (Note: That post assumes you have renamed the extension file to php_mongo.dll.)

If you are new to Windows Azure Web Sites, you’ll need to follow the steps in one of these articles for creating a website before enabling the MongoDB extension:

Create and publish your application

As I mentioned earlier, I’m assuming you have some familiarity with MongoDB and PHP. If you don’t, here’s a good place to get started: http://php.net/manual/en/book.mongo.php. Just for fun, here’s a simple example application (it registers people for an imaginary event) that uses a MongoDB database. You can run it locally or publish to Windows Azure Web Sites. You will need to replace YOUR_CONNECTION_STRING_HERE with the connection string you noted when you created your database, and you’ll need to replace YOUR_DB_NAME_HERE with the name of your database.

<html>

<head>

<Title>Registration Form</Title>

<style type="text/css">

    body { background-color: #fff; border-top: solid 10px #000;

        color: #333; font-size: .85em; margin: 20px; padding: 20px;

        font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;

    }

    h1, h2, h3,{ color: #000; margin-bottom: 0; padding-bottom: 0; }

    h1 { font-size: 2em; }

    h2 { font-size: 1.75em; }

    h3 { font-size: 1.2em; }

    table { margin-top: 0.75em; }

    th { font-size: 1.2em; text-align: left; border: none; padding-left: 0; }

    td { padding: 0.25em 2em 0.25em 0em; border: 0 none; }

</style>

</head>

<body>

<h1>Register here!</h1>

<p>Fill in your name and email address, then click <strong>Submit</strong> to register.</p>

<form method="post" action="index.php" enctype="multipart/form-data" >

      Name  <input type="text" name="name" id="name"/></br>

      Email <input type="text" name="email" id="email"/></br>

      <input type="submit" name="submit" value="Submit" />

</form>

<?php

ini_set("display_errors", "On");

 

try{

    $db = new Mongo("YOUR_CONNECTION_STRING_HERE");

    $registrations = $db->selectCollection('YOUR_DB_NAME_HERE', 'registrations');

} catch (Exception $e){

    echo 'Caught exception: ',  $e->getMessage(), "<br />";

}

 

if(!empty($_POST)) {

    try{

        $registration = array("name" => $_POST['name'], "email" => $_POST['email'], "date" => date("Y-m-d"));

        $registrations->insert($registration);

        echo "<h3>Your're registered!</h3>";

    } catch (Exception $e){

        echo 'Caught exception: ',  $e->getMessage(), "<br />";

    }

}        

 

try{

 

    $registrants = $registrations->find();

 

    if($registrants->count() > 0){

        echo "<h2>People who are registered:</h2>";

        echo "<table>";

        echo "<tr><th>Name</th>";

        echo "<th>Email</th>";

        echo "<th>Date</th></tr>";

        foreach($registrants as $registrant){

            echo "<tr><td>".$registrant['name']."</td>";

            echo "<td>".$registrant['email']."</td>";

            echo "<td>".$registrant['date']."</td></tr>";

        }

        echo "</table>";

    } else {

        echo "<h3>No one is currently registered.</h3>";

    }

} catch (Exception $e) {

    echo "<pre>";

    print_r($e);

    echo "</pre>";

}

?>

</body>

</html>

Note: Instead of hard-wiring the connection string into the code above, you could add it as a Custom string to the connection string section on the CONFIGURE tab of your website’s dashboard. You would then have to modify the code above to retrieve the connection string as an environment variable. More information on how to do that here: Getting Database Connection Information in Windows Azure Web Sites.

To publish your application with Git, follow the instructions here: Publishing with Git.

That’s it. Have fun and let us know what you think.

Thanks.

-Brian


Published at DZone with permission of Brian Swan, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)