PHP中while循环仅执行1次但num_rows为4的问题求助
Hey there! Let's break down exactly what was happening here, and why adding $dirname = "images/main/"; fixed the issue.
The Core Problem: Unreset Variable State
The root cause here is that your $dirname variable was being modified during the first iteration of your loop, and never reset back to its original value for subsequent iterations. Here's a step-by-step breakdown:
First loop iteration:
- You start with
$dirname = "images/main/"; - You build the project folder path using
$dirname . $row['folder_name'] - When you loop through the images in that project folder (your
foreach), your code likely altered the value of$dirname(either directly, or indirectly via an operation that modified the variable in-place)
- You start with
Subsequent loop iterations:
- By the second time your
whileloop ran,$dirnamewas no longer"images/main/"— it was set to the path of the first project's folder (something like"images/main/first_project/") - When you tried to build the next project's path, you ended up with an invalid nested path (e.g.,
"images/main/first_project/second_project/") - This path doesn't exist, so your
foreachfound no images to process. Even though thewhileloop ran all 4 times, only the first iteration produced valid data to add to your JSON array.
- By the second time your
Why the Fix Worked
Adding $dirname = "images/main/"; at the end of your foreach loop ensures that after processing each project, you reset $dirname back to its original base path. This means every iteration of the while loop starts with the correct root directory, so you can properly build each project's folder path and fetch its images.
Quick Example of the Broken vs Fixed Flow
Broken Code Snippet (Simplified):
$dirname = "images/main/"; $result = mysqli_query($conn, "SELECT * FROM projects"); $projects = []; while ($row = mysqli_fetch_assoc($result)) { $projectDir = $dirname . $row['folder_name']; foreach (glob($projectDir . "/*.jpg") as $img) { // Let's say somewhere here you did something like: $dirname = $projectDir; // Oops, modified the base path // Process image... } $projects[] = $projectData; }
Fixed Code Snippet:
$dirname = "images/main/"; $result = mysqli_query($conn, "SELECT * FROM projects"); $projects = []; while ($row = mysqli_fetch_assoc($result)) { $projectDir = $dirname . $row['folder_name']; foreach (glob($projectDir . "/*.jpg") as $img) { // Process image... // No more modifying $dirname here } $dirname = "images/main/"; // Reset base path for next iteration $projects[] = $projectData; }
This reset ensures your path-building logic stays consistent across all 4 rows returned from your query.
内容的提问来源于stack exchange,提问作者Ahmed Nader

