我以为我可以使用MysqLI_STMT_NUM_ROWS和MysqLI_STMT_STORE_RESULT来检查否.返回的行数. (参见注释行/// 1 ///,/// 2 ///,/// 3 ///)
但它似乎不在下面的上下文中.
这段代码确实有效(没有注释行),但我试图添加额外的检查,以确认返回的记录不超过1条. (尽管情况应该总是这样,因为表中的电子邮件字段是唯一的,但无论如何都不会受到影响).
有人能说清楚我做错了吗?
这是我得到的错误(第84行,如果WHILE …行):
An error occurred in script ‘L:\includes\login_functions.inc.PHP’ on line 86: mysqli_fetch_array() expects parameter 1 to be MysqLi_result, boolean given
注意:
这是原始代码的精简版.
$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,并可能导致类似的错误
Commands out of sync; you can’t run this command Now
您可以使用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);
}