What are some best practices for handling SQL queries in PHP when updating a database based on user input?

When updating a database based on user input in PHP, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to execute queries. Additionally, validating and sanitizing user input before using it in a query can help prevent unexpected behavior or errors.

// Assuming $conn is a valid database connection
$userInput = $_POST['user_input'];

// Prepare the SQL statement using a prepared statement
$stmt = $conn->prepare("UPDATE table SET column = ? WHERE id = ?");
$stmt->bind_param("si", $userInput, $id);

// Validate and sanitize user input before using it in the query
$userInput = filter_var($userInput, FILTER_SANITIZE_STRING);

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