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.
<?php 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 r\db("test")->tableCreate("tablePhpTest")->run($conn); // 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 r\db("test")->tableDrop("tablePhpTest")->run($conn);
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
Conclusion
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.
References
Last updated: 16th August 2018
First published: 16th August 2018
First published: 16th August 2018