【问题标题】:PHP: foreach msqli_query issuePHP:foreach msqli_query 问题
【发布时间】:2014-11-07 16:05:01
【问题描述】:

我现在对一小段代码有一个奇怪的问题。我花了太多时间试图弄清楚,所以我想我会在这里问。我有一个整数数组 ($childIDs),我想用它来单独调用 MySQL 数据库中的存储过程。连接设置良好,这种结构直到现在还没有给我带来任何问题。

$childIDs 数组设置正确,foreach 循环确实 将数组中的每个整数作为$currentChild 循环。我首先注意到只有数组中的第一项会显示出来。经过一些测试,我发现 $result 在循环的第一次迭代后被设置为 bool(false)。话虽如此,查询与我在数组中使用的数字一起工作得很好。

所以我的问题是为什么 $result = mysqli_query($database, "CALL get_notes($currentChild);") 除了 foreach 循环的第一次迭代之外的所有内容都是错误的布尔值?

代码如下:

$childIDs = array();
$childIDs = json_decode($_GET['childids']);
$noteList = array();

foreach ($childIDs as $currentChild)
{
  if ($result = mysqli_query($database, "CALL get_notes($currentChild);"))
  {
    // Gathers all the notes for the child
    while($row = mysqli_fetch_array($result))
    {
      // does stuff with each row, for now I'll just use an example...
      var_dump($row);
    }
  }
}

【问题讨论】:

  • 可能是因为 $childIDs 是一组对象而不是关联数组?
  • 如果这是问题所在,为什么它可以与 foreach 循环的第一次迭代一起工作?
  • 我解决了。我回复了解决方案。

标签: php mysql foreach boolean


【解决方案1】:

mysqli_next_result() 解决了这个问题。我需要在每次调用 mysql_query() 的新迭代之前释放 mysqli。这是工作代码:

$childIDs = array();
$childIDs = json_decode($_GET['childids']);
$noteList = array();

foreach ($childIDs as $currentChild)
{
  if ($result = mysqli_query($database, "CALL get_notes($currentChild);"))
  {
    // Gathers all the notes for the child
    while($row = mysqli_fetch_array($result))
    {
      // does stuff with each row, for now I'll just use an example...
      var_dump($row);
    }
  }

  mysqli_next_result($database);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多