无法通过PHP请求从MySQL表中获取数据

时间:2016-01-08 07:51:40

标签: php mysql

我是PHP和MySQL的新手,并试图从我的表中返回一行来匹配HTML表单中的输入。代码如下:

$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) } 

3 个答案:

答案 0 :(得分:1)

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
    }

答案 1 :(得分: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()函数会破坏您的应用程序。抓住错误并将其传递给de view会更好。

答案 2 :(得分: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
}