Wikis & learning

Connect PDO and check the database driver

A database connection begins with a driver name and connection details. This lesson opens a temporary SQLite database in memory so that each run starts with the same empty state.

A database connection begins with a driver name and connection details. This lesson opens a temporary SQLite database in memory so that each run starts with the same empty state.

Walkthrough

PDO provides a common interface while the data source name selects the driver. Applications using MySQL require the corresponding extension, database host and credentials. Keep production credentials in server-side configuration.

PHP example

<?php
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('CREATE TABLE titles (id INTEGER PRIMARY KEY, title TEXT NOT NULL)');
echo $db->getAttribute(PDO::ATTR_DRIVER_NAME), ' connection ready';

Expected output

sqlite connection ready

Change and check

Print the available PDO drivers and confirm sqlite is present. Run the example twice and explain why the inserted table is recreated each time.