【问题标题】:Struggling to Store the SQL fetched results in an Array in PHP努力将 SQL 获取的结果存储在 PHP 中的数组中
【发布时间】:2014-01-06 07:19:04
【问题描述】:

我正在努力将 sql 获取的结果存储在一个数组中。我尝试了很多我在互联网上找到的建议方法,但我无法让它发挥作用。我显然做错了什么。这是我正在测试 atm 的最新代码:

// The following code is place after prepare() and mysqli_stmt_execute($stmt)

    mysqli_stmt_bind_result($stmt, $colDescription);

    $descArray = array();
    $i = 0;

    /* fetch values and store them to each variables */
    while (mysqli_stmt_fetch($stmt)) {          

        $fetch = $colDescription;
        $descArray[$i] = $fetch;
        $i++;
    }

    //For testing to see what echos in that array   
    foreach($descArray as $v) { 
        echo $v;
    }

在上面的代码中,当我回显数组时,只输出了表格的最后一行。所以我认为我基本上将值重叠到最后一行,它并没有真正将所有获取的值存储在一个数组中。我在这里做错了什么?有人可以指导我吗?

【问题讨论】:

  • 显示获取数据的输出
  • 假设应该获取的值是1,2,3,4,5。输出仅显示5,而不是回显完整列表1,2,3,4,5

标签: php mysql sql arrays fetch


【解决方案1】:

据我了解,$colDescription 的值被覆盖。当你在说明中有它时

mysqli_stmt_bind_result($stmt, $colDescription);

现在当你在这里调用它时

$fetch = $colDescription;

它得到了上面初始化的值,所以它写完了。你需要这样做。

unset($colDescription);

在循环之前,以便它从mysqli_stmt_fetch($stmt) 获取新值。所以你的代码应该是这样的

mysqli_stmt_bind_result($stmt, $colDescription);

$descArray = array();
$i = 0;

unset($colDescription);
while (mysqli_stmt_fetch($stmt)) {          

    $fetch = $colDescription;
    $descArray[$i] = $fetch;
    $i++;
}

echo '<pre>';
print_r($descArray);

【讨论】:

  • 如果我在循环之前添加unset($colDescription);,它将无法获取第一个循环本身的结果。使用上述代码时出现此错误:Undefined variable: colDescription in "$fetch = $colDescription;"
【解决方案2】:

在尝试了将近 2 天之后,我无法完全让它与 mysqli 一起工作。所以我切换到PDO,我发现处理获取的数组结果要容易得多。这就是我现在在 PDO 方法中使用的方法,它就像一个魅力:

// The following code is place after PDO prepare() and execute()

    foreach ($stmt as $row) {
        // do something with $row

            $description[] = $row['description'];
    }

您可以看到它是多么容易,并且只需要几行代码就可以做到这一点。当我试图用 mysqli 实现同样的目标时,这就像一场噩梦,我什至不知道这是否可能。我尝试了很多方法都没有运气。即使 mysqli 有可能,我也很确定为了实现这样简单的事情,需要花费很长的风和肮脏的代码。 因此,切换到 PDO 完全值得。

我希望这对像我这样陷入困境的人有所帮助......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2012-07-20
    • 2012-11-05
    • 2021-12-07
    相关资源
    最近更新 更多