2016-01-08 88 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 
}