2014-05-06 28 views
0

我正在做一個簡單的PHP和MySQL IP禁止腳本,並且正處於檢查IP地址是否已被禁止的階段。我創建了一個稱爲test.php測試文件,這是它的內容:選擇沒有正確檢查num_rows的語句

<?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。

+4

*「我的數據庫結構如下:表:banned_ips列1:'id'列2 :'原因'「* --- *愚蠢的問題警報* =>你有一個名爲'ip'的專欄? –

+0

看起來你可能在你的問題上犯了一個錯誤,關於'column 1:id'應該讀作'column 1:ip' ---你的答案在下面。 –

回答

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> 
+0

是的,這是答案。 +1 - 一個額外的解釋將有利於OP。 –

+0

謝謝你的工作,對於錯字感到抱歉,這是我的錯誤。 –

+0

不客氣。犯錯誤是人爲的:-) – bestprogrammerintheworld