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.
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.
// 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 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();
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.
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.