【问题标题】:Why is MySQLi multi_query showing a "Commands out of sync; you can't run this command now" error为什么 MySQLi multi_query 显示“命令不同步;您现在无法运行此命令”错误
【发布时间】:2014-12-04 15:30:06
【问题描述】:

我正在尝试将 0-100 分数转换为 #1、#2、#3、...#n 基准排名。 为了做到这一点,我计划了以下查询:

$q= "SELECT @rownum:=0;";
$q.=" INSERT INTO ranks (`uid`, `rank`, `sample_date`) (SELECT user_id, @rownum:=@rownum+1, NOW() FROM `scores` WHERE 1 ORDER BY score DESC)";

这在 SQL 控制台 (phpmyadmin) 中运行良好,但是当尝试通过 PHP 的 MySQLi 运行时,使用他们的 multi_query 我运行以下错误:

Commands out of sync; you can't run this command now

我的 multi_query 包装器:(在扩展 mysqli 的类中)

public function multiQuery($query) {
    if (@parent::multi_query($query)) {
        $i = 0; 
        do { 
            $i++; 
        } while (@parent::next_result()); 
    }
    if (!$result) {
        printf("MySQLi error:<br><b>%s</b><br>%s <br>", $this->error, $query);
    }

    return $result;
}

为什么会出现这个错误?

【问题讨论】:

  • @CEP 谢谢,但信息量不是很大(没有帮助我理解)
  • 我不是专家,但看来您必须先使用use_result() 的结果,然后才能使用next_result() 继续下一个结果。这个例子应该会有所帮助:php.net/manual/en/…
  • 您想用do-while 循环完成什么?您正在检查 if (!$result),但您之前没有为其分配任何内容。

标签: php mysql mysqli


【解决方案1】:

您必须使用mysqli_store_result()mysqli::use_result() 才能检索查询结果,或继续下一个结果。我相信您正在寻找这样的东西:

public function multiQuery($query)
{
    if (@parent::multi_query($query))
    {
        do
        {
            if ($result = @parent::use_result())
            {
                return $result;
                // this will end the function on the first result encountered.
                // If that is not what you desire, you could create an array of results,
                // and return it after the do-while loop finishes.
            }
            else
            {
                printf("MySQLi error:<br><b>%s</b><br>%s <br>", $this->error, $query);
                return NULL;  // or you could return the error encountered
            }
        } while (@parent::next_result()); 
    }
}

希望对:)有帮助

【讨论】:

猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2013-08-29
相关资源
最近更新 更多