'Unable to display the same data fetched from mysqli database in 2 times [duplicate]
I have fetched an associative array from MySQL database.
When I try to display data using while loop for the first time it behaves normally.
But when I try to use the same while loop 2 times the first one shows the data but the second one is blank.
My code looks as follows
<?php
include 'inc/dbcon.php';
$query = mysqli_query($con, "select * from product");
?>
<select required class="form-control">
<?php
while ($row = mysqli_fetch_assoc($query)) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
<select required class="form-control">
<?php
while ($row = mysqli_fetch_assoc($query)) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
And the out put is like this
Solution 1:[1]
Once a row is fetched from the $query, that row is completely removed from the $query so trying to fetch that row again will return nothing.
So to reuse the $query, you should instead fetch all rows into a variable. Try this
<?php
include 'inc/dbcon.php';
$query = mysqli_query($con, "select * from product");
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
?>
<select required class="form-control">
<?php
foreach ($rows as $row) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
<select required class="form-control">
<?php
foreach ($rows as $row) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

