How can dynamic queries be used in PHP to update database records based on user input?

Dynamic queries in PHP can be used to update database records based on user input by constructing SQL queries using user-provided data. This can be achieved by sanitizing and validating user input to prevent SQL injection attacks. The user input can then be used to dynamically build and execute UPDATE queries to modify the database records accordingly.

// Assuming $conn is the database connection object

// Sanitize and validate user input
$user_id = $_POST['user_id'];
$new_name = mysqli_real_escape_string($conn, $_POST['new_name']);

// Construct and execute dynamic update query
$sql = "UPDATE users SET name = '$new_name' WHERE id = $user_id";
if(mysqli_query($conn, $sql)){
    echo "Record updated successfully";
} else{
    echo "Error updating record: " . mysqli_error($conn);
}