PHP MySQL with PDO

Connect to a database and run safe queries.

✍️ 2 exercises in this lesson

PDO (PHP Data Objects) is the recommended way to work with MySQL and other databases.

  1. Connect: new PDO("mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4", $user, $pass)
  2. Turn on exceptions: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  3. Use prepared statements with placeholders for every value from users.
  4. 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 = ?");
✓ Correct! Not quite. Try again.
Multiple choice

Why use prepared statements?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services