Turso Quickstart (PHP)
Get started with Turso and PHP using the libSQL client in a few simple steps.
In this PHP quickstart we will learn how to:
- Install libSQL Native Extension for PHP (Required)
- Retrieve database credentials
- Connect to a Turso database
- Execute a query using SQL
- Sync changes to local database (optional)
Install libSQL Native Extension for PHP
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:
- Linux
- Mac/Darwin
- Windows (WSL) / Devcontainer
Now, LibSQL
class is available in your PHP environment! You can use it everywhare in your PHP project π
Retrieve database credentials
You will need an existing database to continue. If you donβt have one, create one.
Get the database URL:
turso db show --url <database-name>
Get the database authentication token:
turso db tokens create <database-name>
Assign credentials to the environment variables inside .env
.
TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
Connect
Now connect to your local or remote database using the libSQL connector:
Execute
You can execute SQL queries against your existing database as follows:
<?php
$createUsers = <<<STMT
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
);
INSERT INTO users (name, age) VALUES ('Prof. Ir. Onno Widodo Purbo, M.Eng., Ph.D', 61);
INSERT INTO users (name, age) VALUES ('Jim Geovedi', 41);
INSERT INTO users (name, age) VALUES ('Nasirun', 59);
STMT;
$db->executeBatch($createUsers);
$db->query("SELECT * FROM users")->fetchArray(LibSQL::LIBSQL_ASSOC);
If you need to use placeholders for values, you can do that:
Sync (Embedded Replicas only)
When using embedded replicas you should call sync()
on the database type to sync your local database with the primary database:
<?php
$db->sync();
Was this page helpful?