我想我可以使用MYSQLI_STMT_NUM_ROWS
和MYSQLI_STMT_STORE_RESULT
来检查返回的行数。(请参阅注释行
但它似乎不在下面的上下文中。
此代码确实有效(没有注释的行),但我正在尝试添加额外的检查,以确认返回的记录不超过 1 条。(即使这种情况应该始终如此,因为表中的电子邮件字段是唯一的,但无论如何进行检查也没有什么坏处)。
谁能阐明我做错了什么?
这是我在下面得到的错误(如果WHILE
第 86 行......行):
第 86 行的脚本"L:''include''login_functions.inc.php"中发生错误:mysqli_fetch_array() 期望参数 1 mysqli_result,给定布尔值
注意:
这是原始代码的精简版本。
$form_email
和$form_pass
源自表单输入。
代码是过程性的,因为我喜欢这样。
<?php
// Prepared statement.
$prep_sel = 'SELECT user_id, first_name, user_level, pass FROM users WHERE email=? and active is null';
// Initialise connection.
$stmt_sel = mysqli_stmt_init($dbc);
// Check if there are any DB connection problems.
....
// Prepare statement, bind parameters (an integer and a string) and execute the statement
if (mysqli_stmt_prepare($stmt_sel, $prep_sel)) {
mysqli_stmt_bind_param($stmt_sel, 's', $form_email);
mysqli_stmt_execute($stmt_sel);
///1///mysqli_stmt_store_result($stmt_sel);
}
///2///if (mysqli_stmt_num_rows($stmt_sel) == 1) { // one record found.
// Get the results.
$result = mysqli_stmt_get_result($stmt_sel);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Now check if the passwords match.
if (password_verify($form_pass, $row['pass'])) {
return array(true, $row);
} else {
$errors[] = 'the details you provided does not match our records';
$errors[] = 'your account has not been activated';
}
}
///3///}
/* close statement */
mysqli_stmt_close($stmt_sel);
?>
调用mysqli_stmt_store_result()
后,MySQL驱动程序将不允许您对结果集进行操作,直到获取所有行或释放结果集并关闭语句。 因此,对mysqli_stmt_get_result()
的后续调用将返回false
,并可能导致类似
命令不同步;您现在无法运行此命令
您可以与echo mysqli_error($dbc);
核实
mysqli_stmt_get_result()
传输语句的结果集将使您能够访问其 num_rows
属性,因此您实际上不需要使用 mysqli_stmt_store_result()
。 相反,只需在检查返回的行数之前依赖mysqli_stmt_get_result()
:
if (mysqli_stmt_prepare($stmt_sel, $prep_sel)) {
mysqli_stmt_bind_param($stmt_sel, 's', $form_email);
mysqli_stmt_execute($stmt_sel);
// Transfer the result set here:
$result = mysqli_stmt_get_result($stmt_sel);
// Then check rows returned on the $result obj
// using mysqli_num_rows(), not mysqli_stmt_num_rows()
if (mysqli_num_rows($result) == 1) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Check your password, etc....
}
}
else {
// More than 1, do whatever you need to handle this
}
// Close it
mysqli_stmt_close($stmt_sel);
}
function authenticateUser($email, $password){
$stmt = $db->prepare("SELECT user_id, first_name, user_level, pass FROM users WHERE email=? and active is null");
$stmt->bind_param('s', $email);
$stmt->execute();
$res = $stmt->get_result();
if($res->num_rows > 0){
$hash = $res->fetch_object()->pass;
if(password_verify($password, $hash)){
return true;
}
}
return false;
}
调用函数
if(authenticateUser($_POST['email'], $_POST['password'])){
//do something
}
else{
echo "Invalid Email/Password";
}