使用mysqli和PHP从表中获取用户ID

时间:2014-03-12 22:52:33

标签: php mysql session mysqli fetch

我正在尝试让用户登录并获取他们的ID#39;从我的数据库中的表,所以我可以使用它将SESSION设置为true。我能够让用户登录,但是当我尝试获取用户ID时,我一直得到同样的错误... 警告: mysqli_fetch_assoc()期望参数1为mysqli_result,给定布尔值。 ..这是我的代码:

    if(isset($_POST['login'])){
    $email = $_POST['userEmail'];
    $password = $_POST ['userPass'];
    $passwordHash = md5($password);

    if(!empty($email) && !empty($password)){

        $query = "SELECT email, password FROM users WHERE email=? AND password=?";
        if($stmt = $DB->prepare($query)){   
            $stmt->bind_param('ss',$email,$passwordHash);
            $stmt->execute();
            $stmt->bind_result($email,$passwordHash);
            $stmt->store_result();

            if($stmt->num_rows==1){
                echo 'logged in';
                $getID = mysqli_fetch_assoc(mysqli_query($DB, "SELECT userID FROM users"));
                echo $userID = $getID['userID'];
            }
            else{
                echo 'Invalid Email or Password';
            }
            $stmt->close();
        }
    }
    else{
        echo 'You must enter an email and pass.';
    }

}
$DB->close();

请帮助这对我来说非常令人沮丧。

1 个答案:

答案 0 :(得分:0)

您的查询返回false,因为失败。

在单独的安全页面上,我们会调用restricted/connect.php

<?php
function db(){
  return new mysqli('host', 'username', 'password', 'database');
}
?>

whatever.php页面上:

<?php
include 'restricted/connect.php'; $db = $db();
if(isset($_POST['login'])){
  $cf = 'Connection Failure: ';
  if($db->errno)die($cf.$db->error);
  $email = $_POST['userEmail']; $password = $_POST['userPass'];
  $passwordHash = md5($password);
  if(!empty($email) && !empty($password)){
    if($qry = $db->query("SELECT email, password, userID FROM users WHERE email='$email' AND password='$passwordHash'")){
      if($qry->num_rows > 0){
        $res = $qry->fetch_object(); echo 'Logged in as: '.$res->userID;
      }
      else{
        echo 'Invalid Email or Password';
      }
    }
    else{
      die($cf.$db->error);
    }
    $qry->free();
  }
  else{
    echo 'Please Enter an Email and Password';
  }
}
$db->close();
?>