PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
if database doesn't seem to work right... try echoing your mysql_query... (both of them)... and see what happens. Or use mysql_error(); function... that's all I can tell you so far until you tell us the error. It looks fine to me.
Thanks for all the help. I got it to output data now. But the problem is that it always says:
"you have already rated on this link" also if the row isn't in the database..
if($result = mysql_query("SELECT * FROM rating WHERE rate_ip='$ip' AND rate_link_id='$id'"))
{
echo 'you have already rated on this link';
}
else
{
mysql_query("INSERT INTO rating (rate_ip, rate_link_id, rate_value) VALUES ('$ip', '$id', '$rate')") or die("NONONO");
echo 'inserted';
}
<?php
include('connect.php');
//RATE
$id = $_POST['id'];
$rate = $_POST['rate'];
if (($rate <= 5) && ($rate >= 1))
{$error = false;}
if ($id != NULL && $error == false)
{
$ip = getenv('REMOTE_ADDR');
$sql = "SELECT * FROM rating WHERE rate_ip=$ip AND rate_link_id=$id";
$result = mysql_query($sql); // Execute the query and store it in $result
$num = mysql_num_rows($result); // Get number of rows in $result. 0 if there's not a match, 1 if there's a match.
if($num != 0) // IF $num is not equal to ZERO the record is there, the record does exist, tell them that it's already there.
{
echo 'you have already rated on this link';
}
else // ELSE, there is no row then the record doesn't exist hence the rating is not there, insert it.
{
mysql_query("INSERT INTO rating (rate_ip, rate_link_id, rate_value) VALUES ('$ip', '$id', '$rate')") or die("NONONO");
echo 'inserted';
}
}
?>
Something to that extent. You have to compare two conditions in the if statement, not set something equal to something.
Last edited by dallasx on Sat Oct 22, 2005 12:36 pm, edited 2 times in total.
I will explain the logic in the code I posted above.
First, since you want to use an IF statement, you need to compare two conditions. In your case, you wanted to know whether or not a rating has already been submitted by someone on something based on the IP.
The SQL statement is the key here because you had two things that would make it very, very specific to find only one match which is what you want accomplish. You need to first find the record(s) that exist or don't exist. Once you've got the result stored in the variable $result, you then see how many matches (numbers of rows) that has using the mysql_num_rows(). If the number of rows equals one, then one match was found hence the record exists hence they've already rated it. If the number of rows equals 0, then the record does not exist hence they have not rated it.