Basic CouchDB w/ PHP

I mentioned CouchDB in my last post, but didn’t really elaborate on what it was.

Apache CouchDB is a distributed, fault-tolerant and schema-free document-oriented database accessible via a RESTful HTTP/JSON API. Among other features, it provides robust, incremental replication with bi-directional conflict detection and resolution, and is queryable and indexable using a table-oriented view engine with JavaScript acting as the default view definition language.

I’m gonna show you some really basic ways to use CouchDB using a PHP class found on their website and assume that you have PHP 5.1 or greater and CouchDB 0.8 installed successfully.

The first thing that we need to do is create a sample database for us to play eventually play with using PHP. To manage your databases and documents, you can use Futon, CouchDB’s administrative frontend. It can be accessed at http://localhost:5984/_utils. Create a database called “people” with two documents in it with random IDs that each have two fields in them: “name” and “age”. Also, be sure to enter in some values for those.

Let’s look at this PHP file:

<?php
include_once "CouchDB.php";

$couchdb = new CouchDB("people", "9.57.30.200");
$view = '{ "map": "function(doc) { emit(null, doc); }" }';

try {
  $all = $couchdb->send("/_temp_view", "post", $view)->getBody(true);
}
catch (CouchDBException $e) {
  die("[ERROR]".$e->getMessage()."\n");
}

foreach ($all->rows as $k => $row) {
  echo "Name: ".$row->value->name." / Age: ".$row->value->age."<br/>";
}
?>

This code is using a temporary view to query the database and then simply looping through the returned JSON and printing data from it.  If you set up your database as I mentioned above, $all should be structured like this:

stdClass Object
(
  [total_rows] => 2
  [offset] => 0
  [rows] => Array
  (
    [0] => stdClass Object
    (
      [id] => 4144833052c61ab553875737b88ef91a
      [key] =>
      [value] => stdClass Object
      (
        [_id] => 4144833052c61ab553875737b88ef91a
        [_rev] => 3595404992
        [name] => Ryan
        [age] => 20
      )
    )
    [1] => stdClass Object
    (
      [id] => ff3f20d54772b92aad43c36d6ed4abd1
      [key] =>
      [value] => stdClass Object
      (
        [_id] => ff3f20d54772b92aad43c36d6ed4abd1
        [_rev] => 994830077
        [name] => Bob
        [age] => 40
      )
    )
  )
)

When I visit the page running the script, it will therefore output this:

Name: Ryan / Age: 20
Name: Bob / Age: 40

If anyone wants to see how to do something, just post a comment and I’ll try to whip something up. Also, the CouchDB Wiki has a lot more information if you’re interested.

Leave a Reply