PDO is the recommended way to connect PHP to databases securely. Always use prepared statements with named placeholders like :email to prevent SQL injection. PDO works with MySQL, PostgreSQL, SQLite, and more.
PDO — PHP Data Objects
// Connect
$pdo = new PDO(
"mysql:host=localhost;dbname=shop;charset=utf8mb4",
"user",
"password",
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
// SELECT with prepared statement (safe from SQL injection)
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > :age");
$stmt->execute(["age" => 18]);
$users = $stmt->fetchAll();
// INSERT
$stmt = $pdo->prepare(
"INSERT INTO users (name, email) VALUES (:name, :email)"
);
$stmt->execute(["name" => "Alice", "email" => "a@b.com"]);
$newId = $pdo->lastInsertId();
// Transaction
$pdo->beginTransaction();
try {
$pdo->prepare("UPDATE accounts SET balance=balance-? WHERE id=?")->execute([100, 1]);
$pdo->prepare("UPDATE accounts SET balance=balance+? WHERE id=?")->execute([100, 2]);
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
}