为什么while循环运行一次?

时间:2018-01-12 21:32:17

标签: php mysql mysqli

以下代码只运行一次,而运行的次数是4,有什么帮助吗?

PHP ::

<?php

header("Content-Type: application/json");

require_once("config.php");

if(isset($_GET["m"])) {

    $dirname = "images/main/";
    $arr = array();

    $conn = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);

    if(!$conn) {
        echo "Error connecting to database";
        exit();
    }
    if($stmt = $conn->prepare("SELECT name_ FROM projects")) {
        $stmt->execute();
        $stmt->bind_result($n);
        //$stmt->store_result();
        $result = $stmt->get_result();
        if($result->num_rows == 0) {
            echo "No Projects";
            $stmt->close();
            $conn->close();
            exit();
        }else {
            while ($row = $result->fetch_assoc()) {
                $dirname = $dirname . $row["name_"] . "/";
                $images = glob($dirname . "*.*", GLOB_BRACE);
                foreach($images as $image) {
                    echo $row["name_"];
                    echo$result->num_rows;  // returns 4 !!!!
                    $image = base64_encode($image);
                    //$arr[] = $image;
                    array_push($arr, $image);
                    $image = "";
                }
            }
            echo json_encode($arr);  // returns 1 json row oonly
        }
    }

    $stmt->close();
    $conn->close();
    exit();

}

?>

num rows返回4,为什么它只运行一次或循环一次?

我正在尝试从图像文件夹中获取图像以回显它

FIX ::

根据jhilgeman的回答,我将这部分添加到foreach的末尾:

$dirname = "images/main/";

1 个答案:

答案 0 :(得分:2)

如果我不得不猜测,我会说它正确循环,但问题是这一行:

$dirname = $dirname . $row["name_"] . "/";

每次循环时,您都会将$ row [“name”]值附加到任何$ dirname。所以,让我们说你得到4行像这样:

name
----
houses
boats
computers
animals

在循环开始时,假设$ dirname只是“/ images /”。所以第一个循环会将$ dirname更改为:

/images/houses/

然后第二个循环会将其更改为:

/images/houses/boats/

第三个循环将成为它:

/images/houses/boats/computers/

最后是第四个循环:

/images/houses/boats/computers/animals/

因此,除非您期望以这种方式追加$ dirname,否则您可能希望改为替换$ dirname,而不是每次都附加到它。

请尝试使用此循环:

while ($row = $result->fetch_assoc()) {
  $images_dirname = $dirname . $row["name_"] . "/";
  $images = glob($images_dirname . "*.*", GLOB_BRACE);

  foreach($images as $image) {
    ...etc...
  }
}
相关问题