What are some best practices for updating MySQL tables in PHP when handling likes on different images?

When handling likes on different images in a MySQL database using PHP, it is important to properly update the corresponding table to reflect the changes in likes. One common approach is to have a separate table to store the likes for each image, and update the like count accordingly when a user likes or unlikes an image.

// Assuming you have a table named 'images' to store image data and a table named 'likes' to store likes for each image
// Update the 'likes' table when a user likes an image
$image_id = $_POST['image_id']; // Assuming you have the image id from the form submission

// Check if the user has already liked the image
$liked = $pdo->query("SELECT * FROM likes WHERE user_id = $user_id AND image_id = $image_id")->fetch();

if(!$liked) {
    // If the user hasn't liked the image yet, insert a new like record
    $pdo->query("INSERT INTO likes (user_id, image_id) VALUES ($user_id, $image_id)");

    // Update the like count in the 'images' table
    $pdo->query("UPDATE images SET likes = likes + 1 WHERE id = $image_id");
} else {
    // If the user has already liked the image, remove the like record
    $pdo->query("DELETE FROM likes WHERE user_id = $user_id AND image_id = $image_id");

    // Update the like count in the 'images' table
    $pdo->query("UPDATE images SET likes = likes - 1 WHERE id = $image_id");
}