开发者

Multiple MySQL Queries on One PHP Page

I have the following PHP/MySQL code:

function executeMultirowQuery($query) {
   $result = mysql_query($query);
   $table = array(); 

   if ($result == false) {
      $error = mysql_error();
      echo $error;
   } else {
      while ($row = mysql_fetch_assoc($result)) {
         $table[] = $row;
      }
      mysql_free_result($result);
   }

   return $table;
}

It basically executes the given query, and returns the result as a multi-dimensional array. The second call (and all subsequent calls) to this function result in a "Commands out of sync; you can't run this command now" error from MySQL.

Since I'm calling mysql_free_result() before I return I don't think its that I still have a request out there, but I can't think of any other reason it might be failing.

Any ideas?

EDIT: If it makes any difference, I'm using this function to call stored procedures like this:

function getGroups($groupTypeID) {
   echo "getGroups";
   $query = sprintf("CALL getGroups('%s');", mysql_real_escape_string($groupTypeID));

   return $this->executeMultirowQuery($query);
}

This is typical of the way the executeMultirowQuery() function is used.

EDIT: Here is my connection code:

$this->link = mysql_connect($host, $user, $password);
$success = mysql_select_db($database);

if (!$this->link) {
   die('Could not connect: ' . mysql_error());
}

Also, here is a sample query from the stored procedure:

CREATE DEFINER=`blah`@`blah` PROCEDURE `getGroups`(
    IN inGroupTypeID INT )
BEGIN
   SELECT * FROM `db`.`Groups`
   WHERE GroupTypeID = inGroupTypeID;
END

Again, this is typical of how the function is b开发者_JAVA百科eing used. None of the stored procedures returns multiple results sets (which I understand doesn't work in PHP/MySQL).


A stored procedure returns two resultsets - your data plus a count of the number of rows fetched so you need to call

next_result() 

after each db call.

You'd also be better off using mysqli vs mysql (only the latest mysql extension supports sproc calls) then you can use the faster fetch_all method to populate your array.

$table = $result->fetch_all(MYSQLI_ASSOC);

Hope this helps


I think you should do a mysql_free_result() even when $result == false. Thus, move mysql_free_result($result) outside the else{} and just before the return.

The following links might help:

http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html

http://mike-hostetler.com/blog/2007/04/php-5-and-mysql-5-stored-procedures-error-and-solution-qcodo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜