2016-01-08 126 views
0

我是PHP和MySQL的新手,試圖從我的表中返回一行匹配來自HTML表單的輸入。代碼如下:無法從PHP請求中獲取MySQL表中的數據

$connect = mysqli_connect('localhost', 'root', '', 'testdb') 
OR die('Could not connect to the server' . mysqli_connect_error()); 

$query = ("SELECT * FROM users WHERE username = '$username'"); 
$result = mysqli_query($connect, $query); 
$hits = mysqli_affected_rows($connect); 

if ($hits < 1) { 
    echo "Incorrect password or username"; 
    die("<br /><a href='index.php'>Try Again<a/>"); 
} else { 
    // other not relevant code here 
} 

的VAR $hits總是回來爲0,當有匹配的查詢表中的數據。

var_dump($result)回報:

object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> 
int(4) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) } 
+4

缺少' '''在mysqli_connect(' 本地主機,'和'select'查詢使用'mysqli_num_rows' – Saty

+0

你檢查數據庫連接?此外,通過在打印檢查$ username的值.. –

+0

第一行有語法錯誤mysqli_connect('localhost',... –

回答

0

PLZ後的用戶名... 並嘗試此代碼。

$connect = mysqli_connect('localhost', 'root', '', 'testdb') 
    OR die('Could not connect to the server' . mysqli_connect_error()); 

    $username=$_POST['username']; 

    $query = ("SELECT * FROM users WHERE username = '$username'"); 

    $result = mysqli_query($connect, $query); 
    $hits = mysqli_num_rows($connect); 

    if ($hits < 1) { 
     echo "Incorrect password or username"; 
     die("<br /><a href='index.php'>Try Again<a/>"); 
    } else { 
     // other not relevant code here 
    } 
0

你要算你的結果,而不是受影響的行:

$connect = mysqli_connect('localhost', 'root', '', 'testdb') 
OR die('Could not connect to the server' . mysqli_connect_error()); 

$query = ("SELECT * FROM users WHERE username = '" . mysqli_real_escape_string($username) . "'"); 
$result = mysqli_query($connect, $query); 
$hits = mysqli_num_rows($connect); 

if ($hits < 1) { 
    echo "Incorrect password or username"; 
    die("<br /><a href='index.php'>Try Again<a/>"); 
} else { 
    // other not relevant code here 
} 

另外:不要沒有sanatizing傳遞用戶名。

使用die()函數會中斷您的應用程序。最好趕上錯誤並將其傳遞給觀察者。

+0

引用[來自文檔](http://php.net/manual/en/mysqli.affected-rows.php):'對於SELECT語句mysqli_affected_rows()的作用就像mysqli_num_rows()。'所以這個變化不會做任何東西。 –

+0

@GeraldSchneider http://stackoverflow.com/questions/25555758/what-is-the-difference-between-mysqli-affected-rows-and-mysqli-num-rows – schellingerht

0

使用這樣的:

$connect = mysqli_connect(***'localhost'***, 'root', '', 'testdb') 
OR die('Could not connect to the server' . mysqli_connect_error()); 

$query = ("SELECT * FROM users WHERE username = '" . mysqli_real_escape_string($username) . "'"); 
$result = mysqli_query($connect, $query); 
***$hits = mysqli_num_rows($result);*** 

if ($hits < 1) { 
    echo "Incorrect password or username"; 
    die("<br /><a href='index.php'>Try Again<a/>"); 
} else { 
    // other not relevant code here 
}