PDO (PHP Data Objects) is the recommended way to work with MySQL and other databases.
Connect: new PDO("mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4", $user, $pass)
Turn on exceptions: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
Use prepared statements with placeholders for every value from users.
Fetch rows with fetch() or fetchAll().
Prepared statements prevent SQL injection. Never put $_GET or $_POST values directly into an SQL string.
💡 Key Takeaways: PHP MySQL with PDO
Mastering PHP MySQL with PDO helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
PHP MySQL with PDO Code Example
PHP
<?php
$pdo = new PDO(
"mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4",
"root", "",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
);
// Insert safely
$stmt = $pdo->prepare("INSERT INTO customers (name, city) VALUES (?, ?)");
$stmt->execute(["Ali Traders", "Lahore"]);
echo "New id: " . $pdo->lastInsertId() . "<br>";
// Select safely with a named placeholder
$stmt = $pdo->prepare("SELECT name, city FROM customers WHERE city = :city");
$stmt->execute(["city" => "Lahore"]);
foreach ($stmt->fetchAll() as $row) {
echo "{$row['name']} ({$row['city']})<br>";
}
Output
New id: 11
Ali Traders (Lahore)
Hina Books (Lahore)
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
PHP MySQL with PDO Practice Exercises
Check what you learned in “PHP MySQL with PDO”.
/ 2 solved
Fill in the blank
Prepare a safe query with a placeholder.
$stmt = $pdo->("SELECT * FROM users WHERE id = ?");