What are some alternative approaches to updating a database with user input in PHP to avoid syntax errors and ensure successful data storage?

When updating a database with user input in PHP, it is essential to sanitize and validate the data to prevent syntax errors and ensure successful data storage. One approach is to use prepared statements with parameterized queries to separate the SQL logic from the data input, thus reducing the risk of SQL injection attacks.

// Assume $conn is the database connection object

// Sanitize and validate user input
$user_id = filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
$new_name = filter_var($_POST['new_name'], FILTER_SANITIZE_STRING);

// Prepare the SQL statement with placeholders
$stmt = $conn->prepare("UPDATE users SET name = ? WHERE id = ?");
$stmt->bind_param("si", $new_name, $user_id);

// Execute the statement
$stmt->execute();

// Close the statement and connection
$stmt->close();
$conn->close();