Using fetch_assoc on prepared statements (php mysqli)(在准备好的语句上使用 fetch_assoc (php mysqli))
问题描述
我目前正在编写一个登录脚本,我得到了这个代码:
I'm currently working on a login script, and I got this code:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->execute();
if ($selectUser->num_rows() < 0)
echo "no_user";
else
{
$user = $selectUser->fetch_assoc();
echo $user['id'];
}
这是我得到的错误:
致命错误:未捕获的错误:调用未定义的方法mysqli_stmt::fetch_assoc()
Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetch_assoc()
我尝试了各种变体,例如:
I tried all sorts of variations, like:
$result = $selectUser->execute();
$user = $result->fetch_assoc();
还有更多……没有任何效果.
and more... nothing worked.
推荐答案
那是因为 fetch_assoc 不是 mysqli_stmt 对象的一部分.fetch_assoc 属于 mysqli_result 类.可以使用mysqli_stmt::get_result先获取一个结果对象,然后调用fetch_assoc:
That's because fetch_assoc is not part of a mysqli_stmt object. fetch_assoc belongs to the mysqli_result class. You can use mysqli_stmt::get_result to first get a result object and then call fetch_assoc:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->execute();
$result = $selectUser->get_result();
$assoc = $result->fetch_assoc();
或者,您可以使用 bind_result 将查询的列绑定到变量并使用 fetch() 代替:
Alternatively, you can use bind_result to bind the query's columns to variables and use fetch() instead:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->bind_result($id, $password, $salt);
$selectUser->execute();
while($selectUser->fetch())
{
//$id, $password and $salt contain the values you're looking for
}
这篇关于在准备好的语句上使用 fetch_assoc (php mysqli)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在准备好的语句上使用 fetch_assoc (php mysqli)
基础教程推荐
- php中的foreach复选框POST 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的PDF导出 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
