Skip to main content
SQL Fundamentals
CHAPTER 28 Beginner

Build a PHP SQL CRUD Application | Secure Database Workflow

Updated: May 16, 2026
15 min read

# CHAPTER 28

Building CRUD Applications with SQL

1. Introduction

Connecting to the database was the first step. Now, we must build the application. Every application in existence—from Twitter to massive banking systems—is fundamentally a CRUD application. They allow users to Create, Read, Update, and Delete data. In this chapter, we will synthesize our SQL knowledge with PHP to build the complete backend logic for a Student Management System, implementing absolute security using Prepared Statements.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Map HTTP Form submissions to SQL operations.
  • Execute secure INSERT operations (Create).
  • Execute parameterized SELECT operations (Read).
  • Execute secure UPDATE operations (Update).
  • Execute secure DELETE operations (Delete).
  • Completely immunize your application against SQL Injection.

3. Architecture Setup

Assume we have the following simple table in our database:
sql
12345
CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE
);

*(Assume the $pdo connection variable from Chapter 27 is already established).*

4. CREATE (Inserting Data Safely)

When a user fills out an HTML form and clicks "Submit", the data hits the PHP server. We MUST use Prepared Statements (Chapter 26) to prevent SQL Injection.
php
1234567891011121314151617
<?php
// 1. Data arrives from the frontend form
$name = $_POST[&#039;student_name'];
$email = $_POST[&#039;student_email'];

// 2. Prepare the SQL structure (Using '?' as placeholders)
$sql = "INSERT INTO students (name, email) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);

// 3. Execute the statement, passing the user data securely inside an array!
try {
    $stmt->execute([$name, $email]);
    echo "Student created successfully!";
} catch (\PDOException $e) {
    echo "Error: Email might already exist!";
}
?>

5. READ (Fetching Specific Data)

If an admin wants to search for a student by their ID, we must also parameterize the SELECT statement. Even read operations are vulnerable to injection!
php
12345678910111213141516
<?php
$search_id = $_GET[&#039;id']; // ID from the URL

$sql = "SELECT * FROM students WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$search_id]);

// Fetch a single row as an associative array
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if ($student) {
    echo "Found: " . $student[&#039;name'];
} else {
    echo "Student not found.";
}
?>

6. UPDATE (Modifying Data Safely)

An admin submits a form to update a student's email address. The query requires two parameters: The new email, and the specific ID of the student. The order of the array variables must perfectly match the order of the ? placeholders in the SQL string!
php
12345678910111213
<?php
$new_email = $_POST[&#039;new_email'];
$student_id = $_POST[&#039;student_id'];

// The first '?' is the email. The second '?' is the ID.
$sql = "UPDATE students SET email = ? WHERE id = ?";
$stmt = $pdo->prepare($sql);

// The array order must match the '?' order!
$stmt->execute([$new_email, $student_id]);

echo "Student updated successfully!";
?>

7. DELETE (Removing Data Safely)

An admin clicks the "Delete" button next to a student's name.
php
123456789
<?php
$delete_id = $_POST[&#039;delete_id'];

$sql = "DELETE FROM students WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$delete_id]);

echo "Student permanently removed.";
?>

8. Alternative: Named Parameters

If you have a massive query with 10 placeholders, keeping track of the exact array order for the ? symbols becomes incredibly difficult. PDO offers Named Parameters (using a colon :) which makes the code extremely readable!
php
1234567891011
<?php
// Using :name and :email instead of ?
$sql = "INSERT INTO students (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);

// Pass an associative array. The order no longer matters!
$stmt->execute([
    &#039;:email' => $email,
    &#039;:name'  => $name
]);
?>

9. Common Mistakes

  • Mixing PDO methods: A common beginner mistake is calling $pdo->query() when dealing with user input. The query() method executes raw SQL instantly and bypasses all security. If there is *any* user variable in your SQL, you MUST use $pdo->prepare() followed by execute().

10. Best Practices

  • Redirect After Post (PRG Pattern): When a user successfully creates a student (INSERT), your PHP code should immediately redirect them back to the main page using header("Location: index.php");. If you don't do this, and the user hits the "Refresh" button on their browser, the browser will resubmit the form and insert a duplicate student!

11. Exercises

  1. 1. What two PDO methods must be called sequentially to securely execute a query containing user input?
  1. 2. If you use standard ? placeholders, how does PDO know which variable belongs to which placeholder?

12. SQL Challenges

Write the secure PHP/PDO code utilizing Named Parameters to update the price of a product in the products table, where the product_id matches the target ID.
php
123
$sql = "UPDATE products SET price = :price WHERE product_id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([&#039;:price' => 50.00, ':id' => 10]);

13. MCQ Quiz with Answers

Question 1

When building a CRUD application using PHP Data Objects (PDO), what is the architectural difference between $pdo->query() and $pdo->prepare()?

Question 2

When utilizing standard ? placeholders in a Prepared Statement, what critical rule dictates how the data array is processed during execution?

14. Interview Questions

  • Q: Explain the complete CRUD data flow, detailing how a web application maps the four HTTP methods (POST, GET, PUT, DELETE) to their corresponding SQL commands.
  • Q: A junior developer struggles with a 15-column INSERT statement because they keep messing up the array order for the ? placeholders. What specific feature of PDO would you instruct them to use to solve this problem permanently?

15. FAQs

Q: Do I need to use Prepared Statements if the data comes from an internal source, not a user form? A: Yes! Make it a universal habit. Even internal data can accidentally contain a single quote ('), which will crash a raw SQL string. Prepared Statements handle quote escaping automatically, preventing crashes and security breaches universally.

16. Summary

You are now a Full-Stack Developer. By expertly mapping standard web forms to precise, parameterized CRUD SQL queries, you have bridged the gap between the frontend user interface and the backend relational database, all while maintaining absolute, mathematically guaranteed security against injection attacks.

17. Next Chapter Recommendation

You know all the commands, the security protocols, and the backend integrations. But writing queries is only half the battle. You must know how to design the tables. In Chapter 29: Real-World Database Design Projects, we will step away from the code editor, walk to the whiteboard, and architect complex, enterprise-scale database schemas from scratch.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·