← Back to Chapters

PHP CRUD Class – Usage Example

?️ PHP CRUD Class – Usage Example

? Quick Overview

This topic demonstrates how to use a PHP CRUD class to perform database operations such as INSERT, UPDATE, DELETE, and SELECT in a clean and reusable way.

? Key Concepts

  • Centralized database operations using a single class
  • Reusable methods for common SQL actions
  • Cleaner and maintainable PHP code
  • Improved security using prepared statements

? Syntax & Theory

A CRUD class typically wraps SQL queries inside methods. This allows developers to call simple PHP methods instead of writing SQL repeatedly across files.

? Code Example

? View Code Example
// Include CRUD class and establish database connection
// Insert a new user
$insertData = [
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john.doe@example.com'
];
$crud->insert($insertData);

// Update user email
$updateData = ['email' => 'john.new@example.com'];
$crud->update(1,$updateData);

// Delete a user by ID
$crud->delete(2);

// Fetch all users
$users = $crud->select();
foreach($users as $user){
echo $user['id']." - ".$user['first_name']." ".$user['last_name']." - ".$user['email']."
";
}
?>

? Live Output / Explanation

Expected Result

The script will insert a user, update another user’s email, delete a record, and then display all remaining users from the database.

? Interactive / Visual Flow

Request ➜ CRUD Method ➜ SQL Execution ➜ Database ➜ Result Returned to PHP

? Use Cases

  • User management systems
  • Admin dashboards
  • Content management systems (CMS)
  • REST-style backend logic

✅ Tips & Best Practices

  • Reuse a single CRUD instance across your application
  • Always validate and sanitize user inputs
  • Handle database errors gracefully
  • Log CRUD operations for debugging

? Try It Yourself

  • Insert multiple users using a loop
  • Add a WHERE clause to the select method
  • Implement pagination in SELECT queries
  • Combine CRUD methods to simulate real workflows