【问题标题】:PHP MYSQL Error when calling multiple Stored Procedures调用多个存储过程时出现 PHP MYSQL 错误
【发布时间】:2012-05-24 20:50:05
【问题描述】:

当我在一个页面中多次调用一个过程时,我无法调用和显示内容。我正在尝试显示来自 MYSQL 的两个不同 SP 调用的两个单独的记录集。我可以显示第一个电话,但第二个电话失败。我不确定我做错了什么,但也许有人可以帮忙?

当我调用第二个过程时,我不断收到错误:

Error calling SPCommands out of sync; you can't run this command now

我在 Windows 上运行

下面的代码... PHP

// First call to SP
$page = 2;
$section = 1;

include("DatabaseConnection.php"); //general connection - works fine

$sql = 'CALL GetPageContent("'.$page.'", "'.$section.'")';

$result = mysqli_query($conn, $sql) or die('Error calling SP' .mysqli_error($conn));

while($row=mysqli_fetch_assoc($result))
{
   // DO STUFF< REMOVED TO MAKE READING CLEARER
}

mysqli_free_result($result);

//SECOND CALL BELOW


$section = 2; // change parameter for different results

$sql = 'CALL GetPageContent("'.$page.'", "'.$section.'")';

$result = mysqli_query($conn, $sql) or die('Error calling SP' .mysqli_error($conn));


while($row=mysql_fetch_assoc($result))
{
   // DO STUFF< REMOVED TO MAKE READING CLEARER
}

【问题讨论】:

  • 第二次获取不应该是mysqli_fetch_assoc吗?
  • 是的,但无论哪种方式我仍然得到同样的错误......?谢谢

标签: php stored-procedures mysqli


【解决方案1】:

要解决此问题,请记住在每次存储过程调用后对 mysqli 对象调用 next_result() 函数。请参见下面的示例:

<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');

// Check for errors
if(mysqli_connect_errno()){
 echo mysqli_connect_error();
}

// 1st Query
$result = $db->query("call getUsers()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $user_arr[] = $row;
    }
    // Free result set
    $result->close();
    $db->next_result();
}

// 2nd Query
$result = $db->query("call getGroups()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $group_arr[] = $row;
    }
     // Free result set
     $result->close();
     $db->next_result();
}
else echo($db->error);

// Close connection
$db->close();
?>

【讨论】:

  • 太好了,我不再收到任何错误,但是如何在 while 循环中显示以下内容...非常感谢您的下一步...我之前在while 循环,但现在我收到错误消息:致命错误:无法在 echo "
  • \n" 中使用 stdClass 类型的对象作为数组; echo "\n"; echo "".$row['Text']."";回声“
  • \n”;
  • 先打印 $row var_dump($row);检查它是否返回您所期望的。
  • 【解决方案2】:

    如果您在单个脚本页面上调用多个过程,则应在调用另一个过程之前调用mysqli_next_result($connection_link)。 考虑下面的示例代码块:

    <?php
        $data = new \stdClass();
        require('./controller/dbController.php');
        
        $query = 'CALL getActiveProductCount()';
        $result = mysqli_query($con, $query);
        $result = mysqli_fetch_assoc($result);
        $data->active_product = $result['count'];
        mysqli_next_result($con);  // required to perform before calling the procedure again
    
        $query = 'CALL getPurchasedProductCount()';
        $result = mysqli_query($con, $query);
        $result = mysqli_fetch_assoc($result);
        $data->purchased = $result['count'];
        mysqli_next_result($con);
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签