-1

I have a PHP function called getNumRows:

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;
}

Which uses a Stored Procedure 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;

But it fails on row #1 of my function with:

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

How can I use this procedure to get the number of rows of any table?

xav
  • 5,452
  • 7
  • 48
  • 57
grepsedawk
  • 3,324
  • 2
  • 26
  • 49

1 Answers1

0

I was able to fix it by using this 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;
}
grepsedawk
  • 3,324
  • 2
  • 26
  • 49