This guide connects to a SurrealDB instance with version 2 of the PHP SDK and runs a few basic operations.
1. Install the SDK
Follow the installation guide to add the SDK to your project. Once installed, include the autoloader and import the classes you need.
2. Connect to SurrealDB
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.
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.
3. Create records
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.
4. Retrieve records
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().
5. Run raw SurrealQL
For anything the builders do not cover, run() executes raw SurrealQL. Pass bindings as the second argument to inject values safely.
run() returns one result per statement, so destructure the first entry for a single-statement query.
6. Close the connection
Close the connection when you are done to free resources.