I want to iterate my images using PHP and Mysql While I am using forloop the output is displaying only the last image where presented in MySQL table(last row) EX:
MySql table:
image-1
image-2
image-3
image-4
while using forloop
for ($x = 1; $x <= $rowcount; $x ) {
echo $row['file_name']
?>
Output:
image-4
image-4
image-4
image-4
only displaying the last image. How to resolve this?
CodePudding user response:
You are getting always the same result because the variable inside your loop never changes. Your $row['file_name']
stays the same all the time.
You have to fetch the next row from database result inside the loop.
And, as Alon mentioned, it's better to use a while loop with a fetch function. Since the function (e.g. mysqli_result::fetch_assoc) will return null
when there are no more rows, your loop will end then.
CodePudding user response:
From what you're describing, it seems like your problem is in the logic of the loop itself. You are assigning $x
to 1
and incrementing it with 1
in every iteration, but you're never referencing $x
. You are however referencing $row
which we cannot see the value of. I think you want to use mysqli_fetch_assoc
to extract the row in a while-loop.
Here is an example using mysqli
.
<?php
// Replace this with your credentials.
$servername = 'YOUR_SERVER_NAME';
$username = 'YOUR_USERNAME';
$password = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE';
// Create a connection to the database server.
$connection = mysqli_connect($servername, $username, $password, $dbname);
// Perform a query, selecting file_name from the images table.
$result = mysqli_query($conn, 'SELECT file_name FROM images');
// If mysqli_num_rows returns 0, there are no results.
if (mysqli_num_rows($result) === 0) {
echo 'No results';
} else {
// While $row is assigned to a truthy value, echo out the file_name column.
while($row = mysqli_fetch_assoc($result)) {
echo $row['file_name'] . PHP_EOL;
}
}
The while-loop will continue to execute as long as mysqli_fetch_assoc
returns a row. As soon as all of the rows in the images
table have been iterated, the while loop will not execute anymore, and your script will finish.
CodePudding user response:
Please try this code and change fields and table to your's
$result = mysql_query("SELECT filename, count FROM image_table");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $row[0] . " - " . $row[1];
}