【问题标题】:Loop Through Array using PHP and MySQLi [duplicate]使用 PHP 和 MySQLi 循环遍历数组 [重复]
【发布时间】:2019-09-12 21:30:24
【问题描述】:

我正在尝试使用 PHP 循环遍历 MySQL 表,但它只显示一行。

            //Retrieve a list of outstanding developments
            $sql = "SELECT * FROM tblDevelopment WHERE strStatus=?";
            $statement = mysqli_stmt_init($conn);

            //Check for any errors in the SQL statement
            if (!mysqli_stmt_prepare($statement,$sql)){

                //Report any errors with the prepared $statement
                header("Location: ../sqlerror.php");
                exit();

            } else {

                //If there are no errors, query the database for the username
                mysqli_stmt_bind_param($statement,'s', $status);
                mysqli_stmt_execute($statement);
                $results = mysqli_stmt_get_result($statement);

                if ($row = mysqli_fetch_assoc($results)) {

                    echo 'header';

                    while ($row = mysqli_fetch_assoc($results))
                    {
                         echo $row['strDetail'] . "</";
                    }

                    echo 'footer';

                } else {

                    echo 'No results to display';

                }

            }

代码在没有结果时有效,但当有多个结果时它只显示一个结果 - 知道我做错了什么吗?

【问题讨论】:

  • if 是抓取一条记录。然后是抓住另一个。检查 mysqli_num_rows 以查看有多少记录受到影响。
  • 感谢您的回答 - 我已经取出了 if 位,只是使用了 while,它似乎工作正常。

标签: php mysqli mysqli-fetch-array


【解决方案1】:

您快到了...您需要继续调用mysqli_fetch_assoc,直到您到达结果集的末尾。将您的 if 更改为 while 应该足以让您滚动。

while (($row = mysqli_fetch_assoc($results)) !== null) {

【讨论】:

    猜你喜欢
    • 2016-08-24
    • 2012-02-28
    • 2013-11-23
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2011-05-23
    • 2012-11-14
    相关资源
    最近更新 更多