How can auto_increment be utilized effectively as a primary key in MySQL tables when handling user interactions like liking images in PHP?
When handling user interactions like liking images in PHP, auto_increment can be effectively utilized as a primary key in MySQL tables to ensure each like is uniquely identified. This can be achieved by creating a table to store the likes with an auto_increment primary key column. When a user likes an image, a new record can be inserted into this table with the user's ID and the image ID. This way, each like is associated with a unique identifier for easy retrieval and management.
// Assuming we have a MySQL table named 'likes' with columns: like_id (auto_increment primary key), user_id, image_id
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database_name");
// Get user ID and image ID from the user interaction
$user_id = 1; // Example user ID
$image_id = 123; // Example image ID
// Insert a new like record into the 'likes' table
$query = "INSERT INTO likes (user_id, image_id) VALUES ($user_id, $image_id)";
$mysqli->query($query);
// Check if the like was successfully added
if($mysqli->affected_rows > 0) {
echo "Like added successfully!";
} else {
echo "Error adding like.";
}
// Close the database connection
$mysqli->close();