我想从我的数据库中获取值并将它们分配给变量。这是我的代码。
$stmt = $this->conn->prepare("SELECT ngno, email, encrypted_password, name, user_type FROM `guide` WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$stmt->bind_result($ngno, $email, $encrypted_password, $name, $user_type);
$user = $stmt->fetch();
$stmt->close();
if($encrypted_password == $password){
return $user;
}
} else {
return NULL;
}
我需要将我的表中的值分配给变量$ user并将其返回到我的login.php文件。
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["ngno"] = $user["ngno"];
$response["user"]["email"] = $user["email"];
$response["user"]["name"] = $user["name"];
$response["user"]["user_type"] = $user["user_type"];
echo json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
echo json_encode($response);
}
我的代码似乎没有将值分配给$ user变量。我究竟做错了什么?
答案 0 :(得分:0)
由于我无法发表评论,您是否尝试过:
var_dump($user);
如果它返回NULL,请检查你的方法getUserByEmailAndPassword,尤其是这一行:
$encrypted_password == $password
由于您正在将$ encrypted_password与$ password变量进行比较,您确定要比较的$ password变量是否也是加密(应该是哈希)密码?一旦你回复,将会更新这个答案。
答案 1 :(得分:0)
问题是由于getUserByEmailAndPassword()
方法中的以下语句,
$user = $stmt->fetch();
fetch()
方法将预准备语句的结果提取到绑定变量中,该方法实际返回true
或false
。
以下是参考资料:
而是创建一个数组,比如$user
并将这些绑定的变量值推送到数组中。最后从方法中返回数组。
所以你的getUserByEmailAndPassword()
方法应该是这样的:
public function getUserByEmailAndPassword($email, $password){
$stmt = $this->conn->prepare("SELECT ngno, email, encrypted_password, name, user_type FROM `guide` WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$stmt->bind_result($ngno, $email, $encrypted_password, $name, $user_type);
$user = array();
if($stmt->fetch()){
if($encrypted_password == $password){
$user['ngno'] = $ngno;
$user['email'] = $email;
$user['name'] = $name;
$user['user_type'] = $user_type;
$stmt->close();
return $user;
}else{
return false;
}
}else{
return false;
}
} else {
return false;
}
}