• Start

Languages

/

PHP

/

v2 (alpha)

Quickstart

Connect to SurrealDB with version 2 of the PHP SDK and run your first queries.

This guide connects to a SurrealDB instance with version 2 of the PHP SDK and runs a few basic operations.

Follow the installation guide to add the SDK to your project. Once installed, include the autoloader and import the classes you need.

require __DIR__ . '/vendor/autoload.php';

use SurrealDB\SDK\Surreal;
use SurrealDB\SDK\Connection\ConnectOptions;
use SurrealDB\SDK\Auth\RootAuth;
use SurrealDB\SDK\Types\RecordId;
use SurrealDB\SDK\Types\Table;

$db = new Surreal();

Use the connect() method with a connection string and a ConnectOptions object. The options carry the namespace, database, and authentication details. Passing credentials here lets the SDK re-authenticate automatically after a reconnect.

$db->connect('ws://127.0.0.1:8000/rpc', new ConnectOptions(
namespace: 'surrealdb',
database: 'docs',
authentication: new RootAuth('root', 'root'),
));

WebSocket (ws://) opens a long-lived connection that supports live queries. HTTP (http://) is stateless and suits short-lived requests. See Connecting to SurrealDB for the full set of options.

The create() method starts a CREATE statement. Chain content() to set the record data, then call execute() to run it. Pass a RecordId for a specific ID, or a Table to let SurrealDB generate one.

$person = $db->create(new RecordId('person', 'tobie'))
->content([
'name' => 'Tobie',
'age' => 32,
])
->execute();

$auto = $db->create(new Table('person'))
->content(['name' => 'Jaime'])
->execute();

The select() method reads records. Pass a Table to read all records, or a RecordId to read one. Chain fields(), where(), and limit() to refine the query before execute().

$everyone = $db->select(new Table('person'))->execute();

$tobie = $db->select(new RecordId('person', 'tobie'))->execute();

$adults = $db->select(new Table('person'))
->fields('name', 'age')
->where('age >= 18')
->limit(10)
->execute();

For anything the builders do not cover, run() executes raw SurrealQL. Pass bindings as the second argument to inject values safely.

[$cheapest] = $db->run(
'SELECT name, age FROM person WHERE age < $max ORDER BY age',
['max' => 40],
);

run() returns one result per statement, so destructure the first entry for a single-statement query.

Close the connection when you are done to free resources.

$db->close();

Was this page helpful?