Lesson 18 — Databases

CRUD Operations with MySQL

CRUD — Create, Read, Update, Delete — covers the four basic operations every data-driven application needs, all achievable safely through PDO's prepared statements.

Inserting and Reading Data

Prepared statements separate the SQL structure from the data being inserted, which PDO binds safely — this is the standard defence against SQL injection.

PHP — Insert and select with PDO
// Create
$stmt = $pdo->prepare("INSERT INTO students (name, email) VALUES (:name, :email)");
$stmt->execute(['name' => 'Ayanda', 'email' => 'ayanda@example.com']);

// Read
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = :id");
$stmt->execute(['id' => 1]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

Updating and Deleting

The same prepared-statement pattern applies to updates and deletes, always binding user-provided values rather than concatenating them into the query string.

PHP — Update and delete with PDO
// Update
$stmt = $pdo->prepare("UPDATE students SET email = :email WHERE id = :id");
$stmt->execute(['email' => 'new@example.com', 'id' => 1]);

// Delete
$stmt = $pdo->prepare("DELETE FROM students WHERE id = :id");
$stmt->execute(['id' => 1]);

Common Mistakes

  • Concatenating user input directly into an SQL string instead of using prepared statement placeholders, opening the door to SQL injection.
  • Forgetting to call execute() with the bound values after preparing a statement.
  • Not checking the number of affected rows after an UPDATE or DELETE to confirm the operation actually matched a row.
  • Reusing the same variable names for bound parameters as existing PHP variables, causing confusion about which value is which.

Professional Tip

Never build a query by concatenating variables directly into the SQL string, even for values you believe are "safe". Prepared statements with bound parameters should be the only way user-influenced data ever reaches a query.

Your Turn

Build a small PHP script with functions for creating, reading, updating, and deleting a row in a students table, all using PDO prepared statements.

Mini Quiz

Why are prepared statements the recommended way to include variable data in a SQL query?