/ php

Getting Started With PHP And RethinkDB

Now that we have set up a RethinkDB database, lets dive right into creating a PHP application. Luckily for us, "installing" the RethinkDB driver is as easy as requiring the relevant package. This can be done by executing the following line in your application's directory.

composer require danielmewes/php-rql 2.0.0

Now that you have the "driver" here's an example application that you can copy, paste, and then execute from the CLI. Make sure to change the $dbHost variable.


require_once(__DIR__ . '/vendor/autoload.php');

# Specify the hostname or IP of your rethinkdb database
# this may just be "localhost"
$dbHost = "rethinkdb.programster.org";

 // Connect to localhost
$conn = r\connect($dbHost);

// Create a test table

// Insert a document
$document = array('someKey' => 'someValue');
$result = r\table("tablePhpTest")->insert($document)->run($conn);
echo "Insert: " . print_r($result, true) . PHP_EOL;

// How many documents are in the table?
$result = r\table("tablePhpTest")->count()->run($conn);
echo "Table Document Count: $result\n";

// List the someKey values of the documents in the table
// (using a mapping-function)
$mapFunc = function($x) {
    return $x('someKey');

$result = r\table("tablePhpTest")->map($mapFunc)->run($conn);

foreach ($result as $doc) 
    print "" . print_r($doc, true) . PHP_EOL;

// Delete the test table

The code above will:

  • Connect to the database.
  • Create a test table
  • Insert a document
  • Count how many documents are in the table.
  • Use the map functionality to list all the values in the table that have the key someKey.
  • Drop the test table


You now know how to connect your PHP application to your RethinkDB database. From here you should read the API documents and learn the ReQL query language.


Stuart Page

Stuart Page

Stuart is a software developer with a passion for Linux and open source projects.

Read More