如何使用php中的mysqli_fetch_array从数据库中检索数据

时间:2016-01-19 08:39:33

标签: php database mysqli

如何检索data.here登录不工作。我使用mysqli_fetch_array,但在条件失败之前。

<?php

session_start();
include 'db.php';

$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM tbl-login where   username='".$username."'");
$n = 0;

while($row = mysqli_fetch_array($query)) {
  // $u-id = $row['u-id'];

  $dbusername = $row['username'];
  $dbpassword = $row['password'];
  $usertype = $row['usertype'];
  $_SESSION['usname'] = $dbusername;
  $_SESSION['uid'] = $u-id;
  $_SESSION['usertype'] = $usertype;
  if ($dbusername == $username && $dbpassword == $password) {
    $n++;
    echo "grtet";
    // header('location:dashboard.php');
  }
}

if ($n == 0) {  
  header('location:index.php');
}

?>

3 个答案:

答案 0 :(得分:0)

$query = mysqli_query($connect,"SELECT * FROM tbl-login where   username='".$username."' and password='".$password."'");
$row = mysqli_fetch_row($query); // Just ONE row, because expecting is, there is only one user with this USERNAME
if(empty($row)) {
    echo 'Invalid username or password';
}else{
    echo 'OK :)';
}

答案 1 :(得分:0)

如果您不确定查询失败的原因,请致电mysqli_error()。虽然我没有对自己进行测试,但我相信tbl-login是导致错误的原因(如果你调用它,mysqli_error()应该返回)。

MySQL允许空格和非标识符字符为表/列名称,但在引用此类名称时,需要将其括在反引号(`)之间。因此,tbl-login应该在SQL查询中写为`tbl-login`

答案 2 :(得分:0)

您已将表格名称设为tbl-login,列名称为u-id,变量为$u-id,我认为这是一个问题。如果可能,请更改列名,表名和变量名。以下是一些链接,用于获取创建变量名称,列名称,表名称的基本概念。

Create VariablesCreate TableIdentifiers

我已经更新了你的代码。请看看。

<?php

session_start();
include 'db.php';

$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM `tbl_login` WHERE username='$username' AND password='$password'");

$rowcount = mysqli_num_rows($query);

if($rowcount > 0) {

    while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
        $_SESSION['usname'] = $row['username'];
        $_SESSION['uid'] = $row['u_id'];
        $_SESSION['usertype'] = $row['usertype'];

         header('location:dashboard.php');
    }

} else {

    header('location:index.php');
}
?>