← Back to Chapters

PHP CRUD Class – Update Method

? PHP CRUD Class – Update Method

? Quick Overview

The Update method in a PHP CRUD class is used to modify existing records in a database table. It relies on prepared statements to ensure secure, structured, and maintainable database operations while protecting against SQL injection attacks.

? Key Concepts

  • CRUD stands for Create, Read, Update, Delete
  • Prepared statements improve security and performance
  • Update operations modify existing database rows
  • Affected rows indicate successful updates

? Syntax / Theory

The update method accepts a record ID and updated field values. It prepares an SQL UPDATE query, binds parameters securely, executes the statement, and returns the number of affected rows or false if the operation fails.

? CRUD Class with Update Method

? View Code Example
// PHP CRUD class with an update method using prepared statements
class User {
private $conn;
private $table = "users";

public function __construct($db) {
$this->conn = $db;
}

public function update($id, $first_name, $last_name, $email) {
$stmt = $this->conn->prepare("UPDATE " . $this->table . " SET first_name=?, last_name=?, email=? WHERE id=?");
$stmt->bind_param("sssi", $first_name, $last_name, $email, $id);
if ($stmt->execute()) {
return $stmt->affected_rows;
}
return false;
}
}

? Using the Update Method

? View Code Example
// Using the update method to modify an existing user record
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed");
}

$user = new User($conn);
$rows_updated = $user->update(1, "Jane", "Doe", "jane.doe@example.com");

if ($rows_updated !== false) {
echo "Number of rows updated: " . $rows_updated;
} else {
echo "Update failed.";
}

$conn->close();

? Live Output / Explanation

If the update succeeds, the script outputs the number of rows updated. If no rows are affected or an error occurs, it indicates that the update failed or no changes were detected.

? Interactive Example

You can connect this update logic to an HTML form where users submit updated information. On submission, the form data is passed to the update method, allowing real-time modification of database records.

? Use Cases

  • User profile update systems
  • Admin dashboards for managing records
  • Content management systems
  • Inventory or data maintenance tools

✅ Tips & Best Practices

  • Always validate and sanitize user input
  • Check affected rows to confirm updates
  • Use prepared statements consistently
  • Log update failures for debugging

? Try It Yourself

  • Add more fields like phone number or address to the update method
  • Create an HTML form to update user data dynamically
  • Combine update and read methods to verify changes
  • Implement timestamps to track record updates