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.
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.
1. Install the SDK
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();2. Connect to SurrealDB
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 connectionsHTTP (
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",
]);3. Inserting data into SurrealDB
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,
]);4. Retrieving data from SurrealDB
Selecting records
The select() method retrieves all records from a table, or a single record by its ID.
$everyone = $db->select("person");Running SurrealQL queries
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]
);5. Closing the connection
Always close the connection when you are done to release resources.
$db->close();Next steps
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.
This getting-started guide covers the essentials. For the complete methods, API, and concept reference, see the PHP (v1) SDK reference.