Reputation: 29
I want to print sql result in list using php.
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()) {
$hh=$row['name'];
}
?>
<ul id="myUL">
<li><a href="#"><?php echo $hh ?></a></li>
</ul>
like:-
.Mango
.Apple
.Banana
Upvotes: 0
Views: 2727
Reputation: 3217
$hh
will be the last fetched value because it's being rewritten on every loop cycle. You need to append to that instead. Take a look at this:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query = "SELECT name FROM tablename";
$query = mysqli_query($con, $query)or die("Failed to fetch data");
$lis = "";
// as long as row is not empty
while ($row = $q->fetch_assoc()) {
$lis .= "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "<ul>$lis</ul>";
?>
Upvotes: 1
Reputation: 6693
The issue is that $hh
is always the last row since while($row = $q->fetch_assoc())
over writes the value of the variable with each row.
In order to output a column value in each row, you need to place the output inside of the while loop: it will do it once for each record.
You can use conditional statements for readability:
<!-- Start of List -->
<ul id="myUL">
<?php
$query = "select name from plant ";
$q = mysqli_query($con,$query) or die("Could Not Perform the Query");
while ($row = $q->fetch_assoc()):
?>
<!-- Option -->
<li><a href="#"><?= $row['name']; ?></a></li>
<?php endwhile; ?>
</ul>
<!-- End of List -->
Like referenced by @Cid in the comments, each element needs to be added inside of the list. Keep your <ul>
outside of the loop.
In pseudo code, so you can understand better, it would look like this:
list
foreach row do:
output option
end foreach
end list
Upvotes: 0
Reputation: 158
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
echo "<ul id="myUL">";
while ($row = $q->fetch_assoc()) {
echo "<li> <a href='#'>".$row['name']."</a></li>";
}
echo "</ul>";
?>
Upvotes: 4
Reputation: 15247
Generate the HTML in the for
loop
<?php
$query="select name from plant ";
$q=mysqli_query($con,$query)or die("Could Not Perform the Query");
$hh = ''; //empty string first
while ($row = $q->fetch_assoc())
{
$hh .= '<li><a href="#">' . $row['name'] . '</a></li>';
// ^--------------------- concat with the previous result
}
?>
<ul id="myUL">
<?php echo $hh; /* display */ ?>
</ul>
Upvotes: 2