我之前提出了一个问题,并添加了赏金,但我刚刚意识到我放错了代码。
$getgames = $db->prepare("SELECT `id`, `name`, `picture` FROM `games` WHERE `status` = '1' ORDER BY `id` ASC");
$getgames->execute();
$getgames->bind_result($gid, $name, $picture);
while($getgames->fetch()){
$getgames->free_result();
$gettokens = $db->prepare("SELECT SUM(`amount`) AS `tokenamount` FROM `tokens` WHERE `game` = ? AND `user` = ?");
$gettokens->bind_param('ii', $gid, $sesid);
$gettokens->execute();
$gettokens->bind_result($tokenamount);
$gettokens->fetch();
此代码正确返回第一行,但对于第二行它不显示,并返回以下错误:
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Attempt to read a row while there is no result set associated with the statement'
它所指的行是有$getgames->execute();
的行。
free_result是错误的吗?我还在学习mysql,所以我有很多问题。
更新:当我删除$getgames->free_result();
,然后我得到一个新的错误Commands out of sync; you can't run this command now
。行$getgames->bind_result($gid, $name, $picture);
SELECT query将ALWAYS返回一个结果集。这就是它的工作原理。它可以是空,但它总是存在的,除非在执行过程中出现错误。但是,如果有,错误将是不同的,由prepare或execute调用产生。即使select from空表也会返回一个结果集。
使当前代码不可能出现上述错误信息。
这意味着这个错误是由其他代码引起的。这就涉及到恰当提问的问题。正确询问的问题总是包含完整的错误消息,包括文件名、行号和堆栈跟踪。以及来自OP的注释,指向发布代码中的行,在错误消息中提到。如果OP遵循这个简单的规则,他们会发现错误是由其他代码引起的。
在编辑后的代码中,像这样修改
$getgames->execute();
$getgames->store_result();
$getgames->bind_result($gid, $name, $picture);
while($getgames->fetch()){
$gettokens = $db->prepare( ...
或者最好在一个查询中
SELECT `id`, `name`, `picture`, SUM(`amount`) AS `tokenamount`
FROM `games` g JOIN tokens t ON t.game = g.id
WHERE `status` = '1' AND `user` = ?