• Start

Languages

PHP

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

The PHP SDK for SurrealDB lets you connect to a database and query it from your application. This guide covers connecting, authenticating, and running your first queries.

Note

This guide covers the stable v1 line of the PHP SDK. A v2 rewrite is available in alpha. See the v2 (alpha) getting-started guide.

Follow the installation guide to add the SDK to your project. Once installed, include the autoloader and import the Surreal class.

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

use Surreal\Surreal;

$db = new Surreal();

Use connect() to open a connection, then use() to select the namespace and database you want to work with, and signin() to authenticate. Most operations require both.

Supported connection protocols include:

  • WebSocket (ws://, wss://) for long-lived stateful connections

  • HTTP (http://, https://) for short-lived stateless connections

$db->connect("ws://127.0.0.1:8000/rpc");

$db->use([
    "namespace" => "surrealdb",
    "database" => "docs",
]);

$token = $db->signin([
    "username" => "root",
    "password" => "root",
]);

Once connected, use create() to create records. Pass a record ID such as person:tobie to specify the identifier explicitly, or a table name to generate a random ID.

$person = $db->create("person:tobie", [
    "name" => "Tobie",
    "age" => 32,
]);

The select() method retrieves all records from a table, or a single record by its ID.

$everyone = $db->select("person");

For more advanced use cases, use query() to run SurrealQL statements directly. Use parameters to safely pass dynamic values.

$result = $db->query(
    'SELECT * FROM person WHERE age > $min',
    ["min" => 18]
);

Always close the connection when you are done to release resources.

$db->close();

You have learned how to install the SDK, connect to SurrealDB, create records, and retrieve data. There is a lot more you can do with the SDK, including updating and deleting records, authentication, live queries, and transactions.

Note

This getting-started guide covers the essentials. For the complete methods, API, and concept reference, see the PHP (v1) SDK reference.

Was this page helpful?