Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials PHP MySQL with PHP
PHP Intermediate FREE

MySQL with PHP

Lesson 2 of 17 Intermediate Interactive

PDO (PHP Data Objects) is the recommended way to connect PHP to MySQL databases. It provides a secure, consistent interface for database operations.

Why PDO?

  • Supports multiple databases (MySQL, PostgreSQL, SQLite)
  • Uses prepared statements to prevent SQL injection
  • Has better error handling with exceptions
  • Object-oriented interface

CRUD Operations

  • Create — INSERT INTO
  • Read — SELECT FROM
  • Update — UPDATE SET
  • Delete — DELETE FROM

Important: Always use prepared statements with placeholders (?) or named parameters (:name) to prevent SQL injection attacks.

Syntax

PHP
<?php
// Connect to database

$pdo = new PDO("mysql:host=localhost;dbname=sukhnexus", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Prepared statement — SELECT

$stmt = $pdo->prepare("SELECT * FROM students WHERE course = :course");
$stmt->execute(["course" => "PHP"]);
$students = $stmt->fetchAll();

// INSERT

$stmt = $pdo->prepare("INSERT INTO students (name, email, course) VALUES (?, ?, ?)");
$stmt->execute(["Ali", "ali@test.com", "PHP"]);

// UPDATE

$stmt = $pdo->prepare("UPDATE students SET course = ? WHERE id = ?");
$stmt->execute(["Laravel", 1]);

// DELETE

$stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
$stmt->execute([1]);
?>
PHP and MySQL (PDO)
PHP
<?php
try {
    $pdo = new PDO(
        "mysql:host=localhost;dbname=shop;charset=utf8mb4",
        "root",
        "",
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // Prepared statement (safe)
    $stmt = $pdo->prepare(
        "SELECT * FROM users WHERE email = ?"
    );
    $stmt->execute(["alice@example.com"]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        echo "Found: " . $user["name"] . "
";
    } else {
        echo "No user found
";
    }
} catch (PDOException $e) {
    echo "DB error: " . $e->getMessage() . "
";
}
?>

Practice

1
Exercise

Write a PHP script using PDO to insert a new student record with name, course, and score.

Answer
<?php
$pdo = new PDO("mysql:host=localhost;dbname=sukhnexus", "root", "");
$stmt = $pdo->prepare("INSERT INTO students (name, course, score) VALUES (?, ?, ?)");
$stmt->execute(["New Student", "PHP", 85]);
echo "Student added! ID: " . $pdo->lastInsertId();
?>
2
Exercise

Use a prepared statement with a named placeholder to search for students by course.

Answer
<?php
$pdo = new PDO("mysql:host=localhost;dbname=sukhnexus", "root", "");
$stmt = $pdo->prepare("SELECT * FROM students WHERE course = :course");
$stmt->execute(["course" => "PHP"]);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($students as $s) {
    echo $s["name"] . "<br>";
}
?>

Quick Quiz

1

What does PDO stand for?

PDO stands for PHP Data Objects — a PHP extension for database access.

2

Why are prepared statements important?

Prepared statements separate SQL logic from data, making SQL injection attacks impossible.

3

Which PDO method fetches all rows as an associative array?

fetchAll() returns all result rows as an array.

Interview Questions

mysql_* functions were removed in PHP 7.0 because they are outdated and insecure. PDO is the modern replacement — it supports multiple databases, uses prepared statements by default, handles errors with exceptions, and provides a consistent API. Always use PDO (or mysqli) in new projects.

Prepared statements separate SQL logic from user data, which prevents SQL injection. They also improve performance when executing the same query multiple times with different data, because the SQL is parsed once and executed multiple times. They make code cleaner and more maintainable.