What are the best practices for updating a MySQL table based on user actions in a PHP application?
When updating a MySQL table based on user actions in a PHP application, it is important to sanitize user input to prevent SQL injection attacks. Additionally, use prepared statements to securely interact with the database. Finally, consider implementing error handling to gracefully deal with any issues that may arise during the update process.
// Get user input
$user_id = $_POST['user_id'];
$new_value = $_POST['new_value'];
// Sanitize user input
$user_id = filter_var($user_id, FILTER_SANITIZE_NUMBER_INT);
$new_value = filter_var($new_value, FILTER_SANITIZE_STRING);
// Prepare and execute the update query
$stmt = $pdo->prepare("UPDATE users SET column_name = :new_value WHERE id = :user_id");
$stmt->bindParam(':new_value', $new_value);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
// Check for errors
if($stmt->rowCount() > 0){
echo "Update successful";
} else {
echo "Update failed";
}