Friday, August 17, 2012

PHP-On-Couch

Hi, and welcome to CouchDB Tips! Today, we're going to do some PHP coding, using 5.4 syntax. So, lets get started...

We're going to write a web page that adds a name passed to it by a form, as well as creates and uses a view that employs a composite key. The calling form passes the first name as "first" and the last name as "last". The first thing we need to do is access the PHP-On-Couch library. I put mine in a folder called "PHP_On_Couch" under C:\inetpub\wwwroot. Yes, I use IIS.


<?php
require_once "PHP_On_Couch/lib/couch.php";
require_once "PHP_On_Couch/lib/couchClient.php";
require_once "PHP_On_Couch/lib/couchDocument.php";

Next, we're going to retrieve the user's input:


$first = $_REQUEST['first'];
$last = $_REQUEST['last'];
print "first = $first, last = $last<br />\n";

We need to connect to the CouchDB database. We're calling our database "php_couch3".

$client = new couchClient("http://localhost:5984", "php_couch3");

The next step is to create the database if necessary, and create our view.


if (!$client->databaseExists())
{
  $client->createDatabase();
  $view_fn="function(doc) { if (doc.firstname && doc.lastname) { emit([doc.firstname,doc.lastname], doc); } }";
  $design_doc = new stdClass();
  $design_doc->_id = '_design/all';
  $design_doc->language = 'javascript';
  $design_doc->views = ['by_name' => ['map' => $view_fn]];
  $client->storeDoc($design_doc);
}

This view checks if the document contains an actual name. If it does, it combines the first and last names into a composite key. The next thing we'll do is display all documents whose contents match the input and count them.


$opts = ['key' => [$first, $last]];
$response = $client->setQueryParameters($opts)->getView("all", "by_name");
print_r ($response);

print "<br />\n"; 
print "Found " . count($response->rows) . "<br />\n";


Now, we're going to set up an "auto_increment" and add the new data.

$count = count($client->getView("all", "by_name")->rows);

print "count = $count<br />\n";

$name = new stdClass();
$name->_id = strval($count + 1);
$name->firstname = $first;
$name->lastname = $last;
print "Adding name...<br />\n";

try {
$response = $client->storeDoc($name);
} catch (Exception $e) {
print "Error: ".$e->getMessage()." (errcode=".$e->getCode().")\n";
exit(1);
}

The last thing we're going to do is list all the names in the database.


$response2 = $client->getView("all", "by_name");
foreach ($response2->rows as $name2)
{
# print_r ($name2);
        print $name2->value->_id . ": " . $name2->value->firstname . " " . $name2->value->lastname;
        print "<br />\n";
}
?>

And that's it! I hope you enjoyed this tutorial. Direct all questions to me (Ross Albertson) at euric.reiks@gmail.com. You can find PHP-On-Couch at https://github.com/dready92/PHP-on-Couch/.  I might do C# next.