這是答案會告訴你你應該達到的目標。我不會寫代碼來讓你從你所在的地方走到這裏。但我相信它應該可以幫助你獲得一個好主意。
首先,假設你有一個表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
}
什麼問題?另外:不要使用'mysql_ *'函數,它們已被棄用。 – 2013-03-12 15:21:14
另外,使用'SET Likes = Likes + 1'來確保您的寫入是完全原子的。 – 2013-03-12 15:22:03
嗨!問題是有一個PHP腳本允許用戶只投一次。 – user2120032 2013-03-12 15:22:33