Aral Code

Databases Lesson 16 of 17

PHP and MySQL with PDO — Connect, Query and Prepared Statements

Connect PHP to a MySQL database with PDO, read rows with SELECT, insert, update and delete safely with prepared statements, and prevent SQL injection.

Real web apps keep their data in a database. PHP talks to MySQL (and other databases) through PDO (PHP Data Objects). This lesson shows the safe, modern way to connect and run queries. You should know basic SQL first.

Step 1: Create a database

With XAMPP running, open http://localhost/phpmyadmin, click the SQL tab, and run:

CREATE DATABASE school CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE school;

CREATE TABLE students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  section VARCHAR(30) NOT NULL,
  average DECIMAL(5,2) NOT NULL
);

INSERT INTO students (name, section, average) VALUES
  ('Ana Reyes', 'Rizal', 91.50),
  ('Ben Santos', 'Mabini', 84.00),
  ('Carla Cruz', 'Rizal', 95.20);

Step 2: Connect with PDO

Put the connection in its own file, db.php:

<?php
$pdo = new PDO(
    "mysql:host=localhost;dbname=school;charset=utf8mb4",
    "root",      // XAMPP's default user
    "",          // XAMPP's default password is empty
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
);
  • The first argument (the DSN) says which database type, host and database name to use.
  • ERRMODE_EXCEPTION makes database errors throw exceptions instead of failing silently.
  • FETCH_ASSOC returns rows as associative arrays like ["name" => "Ana Reyes", ...].

Reading rows

<?php
require "db.php";
$rows = $pdo->query("SELECT name, section, average FROM students ORDER BY average DESC")->fetchAll();
foreach ($rows as $r) {
    echo htmlspecialchars($r["name"]) . " ({$r['section']}): {$r['average']}<br>";
}

Browser shows

Carla Cruz (Rizal): 95.20
Ana Reyes (Rizal): 91.50
Ben Santos (Mabini): 84.00

query() is fine when the SQL contains no user input.

SQL injection: the danger of building queries with input

Never paste user input into SQL text:

<?php
// DANGEROUS — never do this
$section = $_GET["section"];
$rows = $pdo->query("SELECT * FROM students WHERE section = '$section'")->fetchAll();

If someone visits ?section=' OR '1'='1, the query becomes WHERE section = '' OR '1'='1', which returns every row. With other input, attackers can read passwords or delete tables. This is SQL injection, one of the most common ways websites get hacked.

Prepared statements: the safe way

<?php
require "db.php";
$section = $_GET["section"] ?? "Rizal";

$stmt = $pdo->prepare("SELECT name, average FROM students WHERE section = ? ORDER BY name");
$stmt->execute([$section]);

foreach ($stmt->fetchAll() as $r) {
    echo htmlspecialchars($r["name"]) . " - {$r['average']}<br>";
}

Browser shows (section=Rizal)

Ana Reyes - 91.50
Carla Cruz - 95.20

The ? is a placeholder. The SQL and the data are sent separately, so the database never treats input as SQL code, no matter what the user types.

Named placeholders

<?php
$stmt = $pdo->prepare("SELECT * FROM students WHERE section = :section AND average >= :min");
$stmt->execute(["section" => "Rizal", "min" => 90]);
$honors = $stmt->fetchAll();

INSERT, UPDATE, DELETE

<?php
require "db.php";

// Insert
$stmt = $pdo->prepare("INSERT INTO students (name, section, average) VALUES (?, ?, ?)");
$stmt->execute(["Dan Lim", "Mabini", 88.75]);
echo "New id: " . $pdo->lastInsertId() . "<br>";

// Update
$stmt = $pdo->prepare("UPDATE students SET average = ? WHERE id = ?");
$stmt->execute([90.00, 2]);
echo "Updated rows: " . $stmt->rowCount() . "<br>";

// Delete
$stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
$stmt->execute([4]);
echo "Deleted rows: " . $stmt->rowCount();

Browser shows

New id: 4
Updated rows: 1
Deleted rows: 1

Getting one row or one value

<?php
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([1]);
$student = $stmt->fetch();          // one row, or false if not found
if (!$student) {
    echo "Not found";
}

$count = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
echo "Total students: $count";

Handling errors

<?php
try {
    require "db.php";
} catch (PDOException $e) {
    error_log($e->getMessage());     // for you, in the server log
    exit("Sorry, the database is unavailable right now.");   // for visitors
}

Don't show raw database errors to visitors: they reveal details about your system.

The security checklist

ThreatDefense
SQL injectionPrepared statements for every query with input
XSShtmlspecialchars on all output
Stolen passwordspassword_hash / password_verify
Bad dataServer-side validation

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What prevents SQL injection?
2. What does ? mean in prepare("... WHERE id = ?")?
3. Which method returns all result rows?
4. Why set PDO::ERRMODE_EXCEPTION?

By Sir Reyel · Last updated 2026-12-04