Databases with PDO
PDO is PHP's database interface for MySQL, PostgreSQL, SQLite and more. Use prepared statements with placeholders so user input is never part of the SQL, which prevents SQL injection. The example uses an in-memory SQLite database.
Example
$pdo = new PDO("sqlite::memory:");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
$stmt = $pdo->prepare("INSERT INTO users (name) VALUES (?)");
foreach (["Ada", "Tunde"] as $n) { $stmt->execute([$n]); }
$q = $pdo->prepare("SELECT * FROM users WHERE name = :n");
$q->execute([":n" => "Tunde"]);
print_r($q->fetch(PDO::FETCH_ASSOC));Result
Array
(
[id] => 2
[name] => Tunde
)Exercise
Use a prepared statement.
$stmt = $pdo->("SELECT * FROM t WHERE id = ?");
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.