选择语句不正确检查num_rows

时间:2014-05-06 14:10:45

标签: php mysql sql

我正在制作一个简单的PHP和MySQL IP禁止脚本,我正处于检查IP地址是否已被禁止的阶段。我创建了一个名为test.php的测试文件,这是它的内容:

<?php
require_once('../includes/db_connect.php');
session_start();

$ip = '1.1.1';
$stmt = $db->prepare("SELECT `ip`, `reason` FROM `banned_ips` WHERE `ip` = ?");
$stmt->bind_param('s', $ip);
$stmt->execute();

if ($stmt->num_rows > 0) {
    header('Location: banned.php');
}

$stmt->close();

 ?>

 <html>
 <h1>This is a test page</h1>
 </html>

正如您所看到的,我已将$ip变量设置为1.1.1,这是一个确实存在于数据库中的测试值,因此应被视为禁止,但它看不到它被禁止,因此不会重定向到被禁止的页面。

在检查数据库中是否已存在IP地址时,我是否做错了什么?

我的数据库结构如下:

表:banned_ips 第1列:id 第2栏:ip 第3栏:reason

编辑:抱歉打字错误,我确实有一个IP列,它是一个varchar。

1 个答案:

答案 0 :(得分:3)

这可能会使它工作:(如果您在数据库中将ip列作为varchar)

<?php
require_once('../includes/db_connect.php');
session_start();

$ip = '1.1.1';
$stmt = $db->prepare("SELECT `ip`, `reason` FROM `banned_ips` WHERE `ip` = ?");
$stmt->bind_param('s', $ip);
$stmt->execute();

//Transfers a result set from the last query
$stmt->store_result(); 

if ($stmt->num_rows > 0) {
    header('Location: banned.php');
}

$stmt->close();

 ?>

 <html>
 <h1>This is a test page</h1>
 </html>
相关问题