What are the best practices for handling database queries in PHP, especially when it involves updating specific data?

When handling database queries in PHP, especially when updating specific data, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, it is recommended to validate user input before executing any queries to avoid errors or unexpected behavior.

// Example of updating specific data in a database using prepared statements

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare the update query with placeholders
$stmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");

// Bind the parameters
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

// Set the values for the parameters
$name = 'John Doe';
$id = 1;

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