这个答案将告诉您您应该实现的目标。我不会编写代码来让您从现在的位置到此。但我相信它应该可以帮助您获得一个好主意。
首先,假设您有一个likes
具有以下结构的表:
user_id INT(11) NOT NULL
video_id INT(11) NOT NULL
PRIMARY KEY(user_id, video_id)
然后,在您的代码中,您可以(我在此示例中使用 PDO,因为我不会容忍使用mysql_*
函数):
$statement = $pdo->prepare('INSERT INTO likes (user_id, video_id) VALUES (:user_id, :video_id)');
$statement->bindValue(':user_id', $userId);
$statement->bindValue(':video_id', $videoId);
try {
// The idea is that, if the user/video combination already exists - the above
// query will throw an exception so you won't execute the code below this line
$statement->execute();
$likes = $pdo->prepare('UPDATE video SET likes = likes + 1 WHERE video_id = :video_id');
$likes->bindValue(':video_id', $videoId);
$likes->execute();
} catch (PDOException $exception) {
// if it was a duplicate key exception, then the likes on the video
// have not been updated and you can print a friendly error message to your
// users here
}