Reputation: 168
I have a database with a table named 'IP' in it. It has 2 columns Id(int11)
and ip(varchar15)
, and a row with values: id 1, ip 127.0.0.1
Now back in PHP I have the following:
$ip = $_SERVER['REMOTE_ADDR'];
$query = "SELECT * FROM ip WHERE ip='$ip'";
if(mysql_query($query)) {
echo "Ip is already in database";
}
else {
echo "Ip is not in database";
}
Now the problem I get is that the if-statement still turns TRUE if I change the IP to say: 125.0.0.1
I have been trying to fix it for 2 hours now but still can't figure out what I'm doing wrong.
Upvotes: 1
Views: 2830
Reputation: 36965
mysql_query()
will not return false if the query executed successfully, even if there are no results. Try using mysql_num_rows()
instead:
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$query = "SELECT * FROM ip WHERE ip='$ip'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo "Ip is already in database";
}
else {
echo "Ip is not in database";
}
By the way I added mysql_real_escape_string
around the REMOTE_ADDR
var, you should always sanitise your input :)
Upvotes: 5
Reputation: 2200
Use mysql_num_rows to check for number of records!
$query = mysql_query("SELECT * FROM ip WHERE ip='". $_SERVER['REMOTE_ADDR'] ."'");
$num = mysql_num_rows($query);
if($num > 0) {
echo "Exists";
}
else {
echo "Does not exist";
}
Upvotes: 4