What are the best practices for updating MySQL data using PHP arrays?
When updating MySQL data using PHP arrays, it is important to properly sanitize and validate the data to prevent SQL injection attacks. One way to achieve this is by using prepared statements with placeholders for dynamic values. This helps separate the SQL query from the data being updated, ensuring that the data is safely inserted into the database.
// Assume $conn is the MySQL database connection
// Sample data to be updated
$data = [
'name' => 'John Doe',
'age' => 30
];
// Prepare the SQL query with placeholders
$sql = "UPDATE users SET name = :name, age = :age WHERE id = :id";
// Prepare the statement
$stmt = $conn->prepare($sql);
// Bind parameters
$stmt->bindParam(':name', $data['name']);
$stmt->bindParam(':age', $data['age']);
$stmt->bindParam(':id', $user_id);
// Execute the statement
$stmt->execute();