我有一个数据库,其中有一个名为' IP'在里面。它有两列Id(int11)
和ip(varchar15)
,以及一行值id 1, ip 127.0.0.1
现在回到PHP我有以下内容:
$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";
}
现在我遇到的问题是,如果我更改IP,if-statement仍会变为TRUE:125.0.0.1
我一直试图将其修复2个小时,但仍然无法弄清楚我做错了什么。
答案 0 :(得分:5)
mysql_query()
将不会返回false,即使没有结果。请尝试使用mysql_num_rows()
代替:
$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";
}
顺便说一下,我在mysql_real_escape_string
var周围加了REMOTE_ADDR
,你应该总是清理你的输入:)
答案 1 :(得分:4)
使用mysql_num_rows检查记录数量!
$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";
}