📅 Week 11 - Day 3: CRUD Operations

Friday | Duration: 3 hours

🎯 Learning Objectives

🔄 What is CRUD?

CRUD stands for the four basic operations for persistent storage:

  • Create - Add new records (INSERT)
  • Read - View existing records (SELECT)
  • Update - Modify existing records (UPDATE)
  • Delete - Remove records (DELETE)

🔄 UPDATE Query

Basic Syntax:

UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;

Update Examples:

-- Update one field UPDATE students SET age = 21 WHERE id = 1; -- Update multiple fields UPDATE students SET name = 'Ahmad Ibrahim', age = 21, course = 'Data Science' WHERE id = 1; -- Update based on condition UPDATE students SET grade = 'A' WHERE age >= 21;

Update with PHP:

<?php require_once 'config.php'; $id = 1; $name = "Ahmad Ibrahim Updated"; $email = "ahmad.new@email.com"; $age = 21; $course = "Data Science"; // Prepare UPDATE statement $stmt = mysqli_prepare($conn, "UPDATE students SET name = ?, email = ?, age = ?, course = ? WHERE id = ?"); mysqli_stmt_bind_param($stmt, "ssisi", $name, $email, $age, $course, $id); if (mysqli_stmt_execute($stmt)) { echo "Student updated successfully!"; } else { echo "Error: " . mysqli_error($conn); } mysqli_stmt_close($stmt); mysqli_close($conn); ?>

❌ DELETE Query

Basic Syntax:

DELETE FROM table_name WHERE condition;

Delete Examples:

-- Delete specific record DELETE FROM students WHERE id = 1; -- Delete based on condition DELETE FROM students WHERE age < 18; -- ⚠️ Delete all records (BE CAREFUL!) DELETE FROM students;

Delete with PHP:

<?php require_once 'config.php'; $id = 5; // Prepare DELETE statement $stmt = mysqli_prepare($conn, "DELETE FROM students WHERE id = ?"); mysqli_stmt_bind_param($stmt, "i", $id); if (mysqli_stmt_execute($stmt)) { if (mysqli_stmt_affected_rows($stmt) > 0) { echo "Student deleted successfully!"; } else { echo "No student found with that ID."; } } else { echo "Error: " . mysqli_error($conn); } mysqli_stmt_close($stmt); mysqli_close($conn); ?>

💻 Complete CRUD Student Management System

1. View All Students (index.php)

<!DOCTYPE html> <html> <head> <title>Student Management System</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; background: #f5f5f5; padding: 20px; } .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; } h1 { color: #667eea; margin-bottom: 30px; } .btn { padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 5px; display: inline-block; margin-bottom: 20px; } .btn-danger { background: #dc3545; } .btn-success { background: #28a745; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { padding: 12px; text-align: left; border: 1px solid #ddd; } th { background: #667eea; color: white; } tr:hover { background: #f5f5f5; } </style> </head> <body> <div class="container"> <h1>Student Management System</h1> <a href="add.php" class="btn">+ Add New Student</a> <?php require_once 'config.php'; $sql = "SELECT * FROM students ORDER BY id DESC"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { echo "<table>"; echo "<thead>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>Name</th>"; echo "<th>Email</th>"; echo "<th>Age</th>"; echo "<th>Course</th>"; echo "<th>Actions</th>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; while ($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . htmlspecialchars($row['name']) . "</td>"; echo "<td>" . htmlspecialchars($row['email']) . "</td>"; echo "<td>" . $row['age'] . "</td>"; echo "<td>" . htmlspecialchars($row['course']) . "</td>"; echo "<td>"; echo "<a href='edit.php?id=" . $row['id'] . "' class='btn btn-success' style='font-size: 12px;'>Edit</a> "; echo "<a href='delete.php?id=" . $row['id'] . "' class='btn btn-danger' style='font-size: 12px;' onclick='return confirm(\"Are you sure?\");'>Delete</a>"; echo "</td>"; echo "</tr>"; } echo "</tbody>"; echo "</table>"; } else { echo "<p>No students found. Add your first student!</p>"; } mysqli_close($conn); ?> </div> </body> </html>

2. Edit Student (edit.php)

<?php require_once 'config.php'; // Get student ID from URL $id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // Fetch current student data $stmt = mysqli_prepare($conn, "SELECT * FROM students WHERE id = ?"); mysqli_stmt_bind_param($stmt, "i", $id); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $student = mysqli_fetch_assoc($result); if (!$student) { die("Student not found!"); } $errors = []; $success = ""; // Handle form submission if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = trim($_POST['name']); $email = trim($_POST['email']); $age = $_POST['age']; $course = $_POST['course']; // Validation if (empty($name)) $errors[] = "Name is required"; if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Valid email is required"; } if (empty($age) || $age < 16) $errors[] = "Valid age required"; // Check if email exists for other students $checkStmt = mysqli_prepare($conn, "SELECT id FROM students WHERE email = ? AND id != ?"); mysqli_stmt_bind_param($checkStmt, "si", $email, $id); mysqli_stmt_execute($checkStmt); mysqli_stmt_store_result($checkStmt); if (mysqli_stmt_num_rows($checkStmt) > 0) { $errors[] = "Email already in use by another student"; } mysqli_stmt_close($checkStmt); // If no errors, update if (empty($errors)) { $updateStmt = mysqli_prepare($conn, "UPDATE students SET name = ?, email = ?, age = ?, course = ? WHERE id = ?"); mysqli_stmt_bind_param($updateStmt, "ssisi", $name, $email, $age, $course, $id); if (mysqli_stmt_execute($updateStmt)) { $success = "Student updated successfully!"; // Refresh data $student['name'] = $name; $student['email'] = $email; $student['age'] = $age; $student['course'] = $course; } else { $errors[] = "Update failed!"; } mysqli_stmt_close($updateStmt); } } mysqli_close($conn); ?> <!DOCTYPE html> <html> <head> <title>Edit Student</title> <style> /* Same styles as registration form */ </style> </head> <body> <div class="form-container"> <h2>Edit Student</h2> <?php if ($success): ?> <div class="success"><?php echo $success; ?></div> <?php endif; ?> <?php if (!empty($errors)): ?> <div class="error"> <ul> <?php foreach ($errors as $error): ?> <li><?php echo htmlspecialchars($error); ?></li> <?php endforeach; ?> </ul> </div> <?php endif; ?> <form method="POST"> <div class="form-group"> <label>Name:</label> <input type="text" name="name" value="<?php echo htmlspecialchars($student['name']); ?>" required> </div> <div class="form-group"> <label>Email:</label> <input type="email" name="email" value="<?php echo htmlspecialchars($student['email']); ?>" required> </div> <div class="form-group"> <label>Age:</label> <input type="number" name="age" value="<?php echo $student['age']; ?>" required> </div> <div class="form-group"> <label>Course:</label> <select name="course" required> <option value="Web Development" <?php echo $student['course'] == 'Web Development' ? 'selected' : ''; ?>>Web Development</option> <option value="Data Science" <?php echo $student['course'] == 'Data Science' ? 'selected' : ''; ?>>Data Science</option> <option value="UI/UX Design" <?php echo $student['course'] == 'UI/UX Design' ? 'selected' : ''; ?>>UI/UX Design</option> </select> </div> <button type="submit">Update Student</button> <a href="index.php" style="display: block; text-align: center; margin-top: 15px;">Back to List</a> </form> </div> </body> </html>

3. Delete Student (delete.php)

<?php require_once 'config.php'; // Get ID from URL $id = isset($_GET['id']) ? (int)$_GET['id'] : 0; if ($id > 0) { // Prepare DELETE statement $stmt = mysqli_prepare($conn, "DELETE FROM students WHERE id = ?"); mysqli_stmt_bind_param($stmt, "i", $id); if (mysqli_stmt_execute($stmt)) { if (mysqli_stmt_affected_rows($stmt) > 0) { $message = "Student deleted successfully!"; } else { $message = "Student not found."; } } else { $message = "Error deleting student."; } mysqli_stmt_close($stmt); } else { $message = "Invalid student ID."; } mysqli_close($conn); // Redirect back to index with message header("Location: index.php?message=" . urlencode($message)); exit(); ?>

✏️ Practice Exercises

  1. Complete the CRUD student management system
  2. Add search functionality by name or course
  3. Implement sorting (by name, age, course)
  4. Add pagination (10 students per page)
  5. Create a "View Details" page for each student

✅ CRUD Best Practices

✅ Today's Deliverable

← Previous Course Home Next Week →