我的查询不起作用

时间:2016-02-08 10:16:01

标签: php database

我正在创建一个连接到数据库的登录脚本,但我得到了一个

  

“未定义的变量:dbUsername in   第21行的F:\ xamp \ register \ login \ functions.php“

我已经进一步检查了它,我发现我的查询不起作用你们可以帮帮我吗?

if (isset($_POST['sub'])) 
{


 include_once("Connect.php");

    $username = strip_tags($_POST['username']);
    $password = strip_tags($_POST['password']);

      $sql = "SELECT id, username, password FROM login WHERE username = '$username' LIMIT 1";

      $query = mysqli_query($dbcon, $sql);

      if ($query) {
        $row = mysqli_fetch_row($query);
        $userId = $row[0];
        $dbUsername = $row[1];
        $dbPassword = $row[2];
      }
      if ($username == $dbUsername && $password == $dbPassword) {
        $_SESSION['username'] = $username;
        $_SESSION['id'] = $userId;
        header('location: login.php');
      } else {
        echo "incorrect username or password.";

      }
    }

2 个答案:

答案 0 :(得分:0)

如果$ query为false,则不设置

$dbUsername$dbPassword

在if语句之前设置$dbUsername = null; $dbPassword = null;

将Where-Query更新为:

"WHERE username = '. $username .'

答案 1 :(得分:0)

您需要在if($query)中使用您的条件,但我认为没有必要重新检查,因为您已经在查询WHERE username = $username.,所以我已将您的代码修改为:

修改后的代码:

  $sql = "SELECT id, username, password FROM login WHERE username = '$username' LIMIT 1";
  $query = mysqli_query($dbcon, $sql);
  if (!$query) {
    die(mysqli_error($dbcon));
  }
  else
  {
    $count = mysqli_num_rows($query); // check total no of rows

    if ($count > 0) 
    {
        session_start(); // start session
        $row = mysqli_fetch_row($query);
        $userId = $row[0]; // get userid from database
        $dbUsername = $row[1]; // get username from database
        $_SESSION['username'] = $dbUsername;
        $_SESSION['id'] = intval($userId);
        header('location: login.php');    
        die(); // using die() after header()
    }
    else{
        echo "incorrect username or password."; // if query not return anything print this.
    }  
  }