命令不同步;你现在无法在$ mysqli-> prepare上运行此命令

时间:2014-03-24 20:57:19

标签: php stored-procedures mysqli

我有一个名为getNumRows的PHP函数:

function getNumRows() {
    $query = $this->mysqli->prepare("CALL GetNumRows('$this->tableName')") or die('Unable to prepare: ' . $this->mysqli->error);
    $query->execute();
    $query->store_result();
    $query->bind_result($rowCount);
    while ($query->fetch()) {
        $numRows = $rowCount;
    }
    $query->close();

    return $numRows;
}

使用存储过程CALL GetNumRows('TableName')

DROP PROCEDURE gpstrack.GetNumRows;
CREATE DEFINER=`******`@`localhost` PROCEDURE `GetNumRows`( IN tab_name VARCHAR( 40 ) )
BEGIN 
SET @t1 = CONCAT(  'SELECT COUNT(*) FROM ', tab_name) ;
PREPARE stmt3 FROM @t1 ;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END;

但是我的功能的第一行失败了:

Unable to prepare: Commands out of sync; you can't run this command now

如何使用此过程获取任何表的行数?

1 个答案:

答案 0 :(得分:0)

我能够通过使用这个PHP修复它:

function getNumRows()
{
    $query = $this->mysqli->prepare("CALL GetNumRows('$this->tableName')") or die('Unable to prepare: ' . $this->mysqli->error);

    $query->execute();
    $query->store_result();
    $query->bind_result($rowCount);
    $query->fetch();
    $numRows = $rowCount;
    $this->mysqli->next_result();// ADDED THIS LINE
    $query->close();

    return $numRows;
}