arrow_back
Back

PDO in PHP: drivers, connections, queries, and inserts

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

PDO (PHP Data Objects) is a database access layer that provides a uniform API across different drivers (MySQL, SQLite, and others).

Available drivers

List installed PDO drivers:

print_r(PDO::getAvailableDrivers());

Connecting

try {
    // MySQL via PDO_MYSQL
    $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

    // SQLite
    $dbh = new PDO("sqlite:my/database/path/database.db");
} catch (PDOException $e) {
    echo $e->getMessage();
}

Connection attributes

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

Closing a connection

Set the connection variable to null:

$dbh = null;

Creating a table

$dbh->exec("CREATE TABLE IF NOT EXISTS messages (
    id INTEGER PRIMARY KEY,
    title TEXT,
    message TEXT,
    time INTEGER
)");

Another example:

$dbh->exec("CREATE TABLE IF NOT EXISTS followers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    facebook_id TEXT
)");

SELECT

$result = $dbh->query("SELECT id FROM spreadsheet WHERE status = 1 AND thread IS NULL");

Inserting a row

$sth = $this->dbh->prepare("INSERT INTO links (link, processed) VALUES (:link, 0)");
$sth->execute([':link' => $url]);
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

SQLite in PHP: file databases with PDO

arrow_forward