检查数据库中是否存在IP地址 [英] Check whether an IP address is stored in database

查看:184
本文介绍了检查数据库中是否存在IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库,其中有一个名为IP的表。它有两列 Id(int11) ip(varchar15),以及一个值为 id 1,ip 127.0.0.1

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

现在回到PHP我有以下:

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";
}



现在我得到的问题是if语句仍然变为TRUE如果我改变IP说: 125.0.0.1

我一直试图修复它2小时,找不到我做错了什么。

I have been trying to fix it for 2 hours now but still can't figure out what I'm doing wrong.

推荐答案

mysql_query()没有结果。尝试使用 mysql_num_rows()

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";
}

顺便说一下,我添加了 mysql_real_escape_string REMOTE_ADDR 周围,您应该总是清除您的输入:)

By the way I added mysql_real_escape_string around the REMOTE_ADDR var, you should always sanitise your input :)

这篇关于检查数据库中是否存在IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆