# PHP

Connect to ParticleDB from PHP, run parameterized queries, handle transactions and errors.

Source: https://particledb.ai/sdks/php/

Use the configured address for your client. See [connection addresses](/installation/ports/) and [security](/guides/security/). The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.

Use PDO with the `pdo_pgsql`
extension over the SQL client interface (port 5432): prepared statements, transactions, and
Handle SQLSTATE error codes through the client error API.

Check that the extension is loaded with `php -m | grep pdo_pgsql`.

## Quick start

The example connects as `postgres` with the password `secret`, for a server started with
`particledb start --auth-method scram-sha-256 --pg-password secret`. With the server's default
`--auth-method password`, add `sslmode=require` to the DSN; see
[TLS and authentication](/connectivity/tls/#authentication).

```php
<?php
$pdo = new PDO('pgsql:host=localhost;port=5432;dbname=particledb', 'postgres', 'secret', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$pdo->exec('CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT)');

$stmt = $pdo->prepare('INSERT INTO users (id, name) VALUES (?, ?)');
$stmt->execute([1, 'Alice']);
echo $stmt->rowCount() . "\n";   // 1

$stmt = $pdo->prepare('SELECT id, name FROM users WHERE id = ?');
$stmt->execute([1]);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    echo $row['id'] . ' ' . $row['name'] . "\n";
}

$pdo->beginTransaction();
$pdo->prepare('UPDATE users SET name = ? WHERE id = ?')->execute(['Bob', 1]);
$pdo->commit();   // or rollBack()

echo $pdo->query('SELECT name FROM users WHERE id = 1')->fetchColumn() . "\n";   // Bob

try {
    $pdo->exec('SELECT * FROM missing_table');
} catch (PDOException $e) {
    echo $e->getCode() . "\n";   // 42P01
}
```

Output:

```
1
1 Alice
Bob
42P01
```

Key-value operations and vector search are SQL, so you run them through PDO like any other
statement, for example `$pdo->prepare('SELECT KV_GET(?)')`. See
[Vector Search](/sql/vector-search/).

## Next steps

- [SQL Reference](/sql/overview/). SQL syntax and examples
- [ORM compatibility](/connectivity/orm-compatibility/). ORMs tested against ParticleDB
- [SQL client connections](/connectivity/pg-wire/). connection settings and compatibility
