I am using the below code to insert ratings for specific songs on my application.
I am recording the songID, the rating given to the song and the userID who has voted on the song.
What I want to do is to prevent a user from voting if they have 'already' voted on a specific song. Therefore I need to be able to check if a row exists in the table before insertion.
So... If userID = 1, songID = 1 and rating = 4. This should insert fine.
If subsequently, an insertion attempt is made for userID=1, songID=1, rating=*, it should fail to insert
However if the user is voting on a different song... that should be allowed and the insertion should happen.
Any ideas how I would go about this?
//Add rating to database
if(!empty($_POST['rating']) && isset($_POST))
{
//make variables safe to insert
$rating = mysql_real_escape_string($_POST['rating']);
$songid = mysql_real_escape_string($_POST['song_id']);
//query to insert data into table
$sql = "
INSERT INTO wp_song_ratings
SET
songid = '$songid',
rating = '$rating',
userid = '$user_id'";
$result = mysql_query($sql);
if(!$result)
{
echo "Failed to insert record";
}
else
{
echo "Record inserted successfully";
}
}