PDA

View Full Version : Check If An Entry Exists


Candrias77
04-27-2003, 01:53 PM
Hi again, I am trying to check my database to see if there is an entry where two values in a row match.

I have a table which records information on ratings that each user has given each movie, it looks a little like this:


Table = USER_VOTES

USER_ID MOVIE_ID VOTE
1 2 5
2 3 5
3 4 5
3 5 5
4 3 5

I an using a simple SELECT command to find if a user has already voted, ie. if a row already exists with their USER_ID and MOVIE_ID. I am having a little trouble with this SELECT statement and wonder if there is a better way of doing this simple check. My code looks like this:


$sql = "SELECT vote FROM user_votes WHERE movie_id='$id' && user_id='$usrID'";
if ($result = mysql_query($sql, $db)) {
//if vote already exists display error
$error = "You have already voted for this moive
(your rating was ".mysql_result($result,0,"vote").").";
} else {
//if no vote exists process vote...
}

If a user has not voted before I get an error like this:
Unable to jump to row 0 on MySQL result index 2

To me it appears that mysql_query() does not return false when no results are found. Is there a command which does check results and return false or is there a much easier way to check, perhaps there could be some checking code in the actual SQL query???

Thanks, any thoughts are appreciated as always.

Candrias77
04-27-2003, 02:05 PM
Ok, for now I have this solution which works:


$sql = "SELECT vote FROM user_votes WHERE movie_id='$id' && user_id='$usrID'";
$result = mysql_query($sql, $db);
if (mysql_num_rows($result)) {
//if vote already exists display error
//etc. etc. etc.
But I am still interested in your thoughts on a cleaner way of doing this, thanks.