Skip to content

Connecting to SQLite using PHP

SQLite is a lightweight, serverless database engine that integrates seamlessly with PHP. On ruachost.com, you can connect to SQLite databases using PHP’s built‑in PDO (PHP Data Objects) extension.

  • No external server required — databases are stored in a single file.
  • Perfect for lightweight applications, prototyping, and local development.
  • PDO provides a consistent interface across multiple database systems.
  • Easy to deploy and portable across environments.
  • Verify that the pdo_sqlite extension is enabled in your PHP configuration.

  • You can check by running:

    <?php phpinfo(); ?>

Use PDO to connect to an existing SQLite database file (or create one if it doesn’t exist).

<?php
try {
// Connect to SQLite database file
$pdo = new PDO('sqlite:/home/username/path/example.db');
// Set error mode to exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to SQLite successfully!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
  • Replace /home/username/path/example.db with the actual path to your database file.
  • If the file does not exist, SQLite will create it automatically.
<?php
$result = $pdo->query("SELECT lastname FROM employees");
foreach ($result as $row) {
echo $row['lastname'] . "<br>";
}
?>