pdo driver for pglite & php-wasm
pdo_pglite requires PHP 8.1+
Simply pass the PGlite object into the php-wasm constructor to enable pdo_pglite support:
import { PGlite } from '@electric-sql/pglite';
const php = new PhpWeb({PGlite});
You can even load PGlite from a CDN:
import { PGlite } from 'https://cdn.jsdelivr.net/npm/@electric-sql/pglite/dist/index.js';
const php = new PhpWeb({PGlite});
Once PGlite is passed in, pgsql:
will be available as a PDO driver.
import { PGlite } from 'https://cdn.jsdelivr.net/npm/@electric-sql/pglite/dist/index.js';
const php = new PhpWeb({PGlite});
php.run(`<?php
$pdo = new PDO('pgsql:idb-storage');
`);
Use pdo-pglite like you'd use any other PDO connector. Prepared statements, as well as positional & named placeholders are supported.
import { PGlite } from '@electric-sql/pglite';
const php = new PhpWeb({PGlite});
php.run(`<?php
$pdo = new PDO('pgsql:idb-storage');
$stm = $pdo->prepare(
'SELECT * FROM pg_catalog.pg_tables WHERE schemaname = :schema'
);
$out = fopen('php://stdout', 'w');
$stm->execute([
'schema' => 'pg_catalog'
]);
$headers = false;
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
if (!$headers) {
fputcsv($out, array_keys($row));
$headers = true;
}
fputcsv($out, $row);
}
`);
PGlite can also be used right from static HTML. Just pass it in the data-imports
attribute on the php script tag:
<html>
<body>
<script async type = "module" src = "./php-tags.mjs"></script>
<script type = "text/php" data-stdout = "#output" data-stderr = "#error" data-imports = '{
"https://cdn.jsdelivr.net/npm/@electric-sql/pglite/dist/index.js": ["PGlite"]
}'><?php
$pdo = new PDO('pgsql:idb-storage');
$stm = $pdo->prepare(
'SELECT * FROM pg_catalog.pg_tables WHERE schemaname = :schema'
);
$out = fopen('php://stdout', 'w');
$stm->execute([
'schema' => 'pg_catalog'
]);
$headers = false;
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
if (!$headers) {
fputcsv($out, array_keys($row));
$headers = true;
}
fputcsv($out, $row);
}
</script>
<pre id = "output"></pre>
<pre id = "error"></pre>
</body>
</html>
pdo_pglite
is powered by @electric-sql/pglite.