【问题标题】:why the while loop runs once?为什么while循环运行一次?
【发布时间】:2018-01-12 21:32:16
【问题描述】:

下面的代码只运行一次,而它应该运行的次数是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 为什么它只运行或循环一次?

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

修复::

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

$dirname = "images/main/";

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

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

    $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 以这种方式附加,否则您可能希望替换为 REPLACE $dirname 而不是每次都附加到它。

    在你的循环中试试这个:

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

    【讨论】:

    • 谢谢,它成功了,我不知道我怎么想不通!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2011-11-02
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多