The libSQL Native Extension for PHP contains everything you need to work with Turso and works flawlessly with all features, because itโ€™s build on top libSQL Rust crate and ext-php-rs framework to create a new PHP Extension with easy.

Installing

Before your start using libSQL in PHP, you need to install and configure your PHP environment.

Download the latest build extension/driver binary you can see at Release page. It's available for:

Now, LibSQL class is available in your PHP environment! You can use it everywhare in your PHP project ๐ŸŽ‰

Initializing

Depending on where and how you plan to use libSQL, you can use a variety of connection types. You can connect to a local database, a remote database, or an in-memory database.

In-Memory Databases

libSQL supports connecting to in-memory databases for cases where you donโ€™t require persistence:

$db = new LibSQL(":memory:");

Local Development

Establishing a connection to a local database is straightforward with LibSQL. You have 3 options:

  1. Standard DSN Connection: If youโ€™re using a DSN string, use the following format:

    $db = new LibSQL("libsql:dbname=database.db", LibSQL::OPEN_READWRITE | LibSQL::OPEN_CREATE, "");
    
    • This option utilizes a Data Source Name (DSN) string to specify the database location.
    • The DSN format is libsql:dbname=database.db.
    • Additional parameters include connection flags and an optional encryption key.
  2. Standard SQLite Connection: For direct SQLite connections, simply provide the database file name:

    $db = new LibSQL("database.db", LibSQL::OPEN_READWRITE | LibSQL::OPEN_CREATE, "");
    
    • In this setup, the database filename alone is provided, without a DSN.
    • The database file name is directly specified, e.g., "database.db".
    • Similar to the DSN connection, it also allows for setting connection flags and an optional encryption key.
  3. Standard LibSQL Connection: Alternatively, you can specify the file protocol explicitly:

    $db = new LibSQL("file:database.db", LibSQL::OPEN_READWRITE | LibSQL::OPEN_CREATE, "");
    
    • This option resembles the DSN connection but uses the file protocol in the DSN string.
    • The DSN string format is "file:database.db".
    • Connection flags and an encryption key can also be specified.

Remote Connection

For remote databases, you can pass your database URL libsql:// or https:// URL to the LibSQL constructor:

$db = new LibSQL("libsql:dbname=libsql://[databaseName]-[organizationName].turso.io;authToken=...");

Embedded Replicas

You can work with embedded replicas by passing your Turso Database URL to syncUrl:

<?php

$config = [
    "url" => "file:database.db",
    "syncUrl" => getenv('TURSO_DATABASE_URL'),
    "authToken" => getenv('TURSO_AUTH_TOKEN')
];

$db = new LibSQL($config);
url
string
required

Specifies the local database path filename using relative path /home/turso/app/database.db remember the back-slash at the begining.

authToken
string
required

Authentication token for secure access. Generate from Get the database authentication token command

syncUrl
string
required

URL for synchronization purposes. generate from Get the database URL command

syncInterval
integer

Integer value representing synchronization interval in seconds (optional, default: 5).

read_your_writes
boolean

Boolean value indicating whether to read your writes (optional, default: true).

encryptionKey
string

String value for encryption purposes (optional, default: empty).

Simple Query

You can pass a string to execute() to invoke a SQL statement, as well as optional arguments:

<?php

$db->query("SELECT * FROM users", ())->fetchArray();

You can pass constant in fetchArray method: LibSQL::LIBSQL_ASSOC, LibSQL::LIBSQL_NUM, LibSQL::LIBSQL_BOTH, or LibSQL::LIBSQL_ALL, default is LibSQL::LIBSQL_BOTH.

Prepared Statements

You can prepare a cached statement using prepare() and then execute it with query():

<?php

$stmt = $db->prepare("SELECT * FROM users");
$stmt->query()->fetchArray();

You can pass constant in fetchArray method: LibSQL::LIBSQL_ASSOC, LibSQL::LIBSQL_NUM, LibSQL::LIBSQL_BOTH, or LibSQL::LIBSQL_ALL, default is LibSQL::LIBSQL_BOTH.

Placeholders

libSQL supports the use of positional and named placeholders within SQL statements:

<?php

$db->query("SELECT * FROM users WHERE id = ?", [1])->fetchArray();

Batch Transactions

A batch consists of multiple SQL statements executed sequentially within an implicit transaction. The backend handles the transaction: success commits all changes, while any failure results in a full rollback with no modifications.

<?php

$db.executeBatch("
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL
  );

  INSERT INTO users (name) VALUES ('Alice');
  INSERT INTO users (name) VALUES ('Bob');
");

Interactive Transactions

Interactive transactions in SQLite ensure the consistency of a series of read and write operations within a transactionโ€™s scope. These transactions give you control over when to commit or roll back changes, isolating them from other client activity.

  • transaction() โ€” with default transaction behavior (DEFFERED)
  • You can set another bahavior like: (DEFFERED, WRITE, READ)
<?php

$tx = $db->transaction();

$tx->execute("INSERT INTO users (name) VALUES (?1)", ["Iku"]);
$tx->execute("INSERT INTO users (name) VALUES (?1)", ["Iku 2"]);

$tx->commit();