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><?php echo $hh ?></li>
</ul>
like:-
.Mango
.Apple
.Banana
<?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>";
?>
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>' . $row['name'] . '</li>';
// ^--------------------- concat with the previous result
}
?>
<ul id="myUL">
<?php echo $hh; /* display */ ?>
</ul>
$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>";
?>
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><?= $row['name']; ?></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
Related
I'm playing around with PHP a bit and am trying out dynamic links. My problem is that the corresponding ID is not correctly to the URL with my code, so I have the same link everytime.
Here is what I have:
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
mysqli_select_db($connection, 'filme');
$query = "SELECT * FROM filme";
$result = mysqli_query($connection, $query);
$filmID = mysqli_fetch_assoc($result);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row['Name'] . " - " . $row['Preis'];
}
$chunks = array_chunk($array, 4);
$filmID = mysqli_fetch_assoc($result);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $val) {
?><td><?php echo $val; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysql_close();
?>
What I'm trying to do is display a table with four columns, that in every cell has a string in the format of "Film name - Price" and this string should be a link that leads to the page with the according ID. This code does display my four column table, but it is missing the first item of my database and the ID is the same for every link, namely the ID of that first film that is missing. So every URL looks like this:
http://localhost/dvd.php?Film_ID=1000
But the film with the ID 1000 is not even listed. I thought about putting that nested foreach loop in a while loop with
while($filmID = mysqli_fetch_assoc($result)){
...
}
But with that I get a blank page.
I have just about no experience with php, so sorry if I'm missing something really obvious.
You are going about this the wrong way. There's no link here between the contents of $array and $filmID. Indeed, $filmID is probably empty because you've already run through your result set earlier. Imagine your database result set is like a stack of papers. Each call to fetchAssoc() reads one sheet of paper, and sets it aside. Once you reach the end of the result set, there's nothing left to read, so your next calls will fail. You need to do all your database fetch in a single loop. As well, you should not be using mysql_close() with mysqli.
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
$connection->select_db('filme');
$query = "SELECT * FROM filme";
$result = $connection->query($query);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
$chunks = array_chunk($array, 4);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $film) {
?><td><?php echo "$film[Name] - $film[Preis]"; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysqli_close();
Or, better yet, just use the more modern PDO library:
<?php
$connection = new PDO("mysql:host=localhost;dbname=filme", "root", "password");
$query = "SELECT `Film_ID`, `Name`, `Preis` FROM filme";
$result = $connection->query($query);
$chunks = array_chunk($result->fetchAll(PDO::FETCH_ASSOC), 4);
?>
<table class='filme'>
<?php foreach ($chunks as $chunk):?>
<tr>
<?php foreach ($chunk as $film):?>
<td>
<?=htmlspecialchars("$film[Name] - $film[Preis]")?>
</td>
<?php endforeach?>
</tr>
<?php endforeach?>
</table>
Note this code is much more efficient and easier to read due to use of alternative syntax and short echo tags to keep PHP and HTML mixing to a minimum. Ideally your PHP would be in a totally separate file.
I'm trying to get this information out of the database:
$query = "SELECT * FROM station_control WHERE station_no > 0 ORDER BY station_ord";
it then says it expects parameters in these two lines:
$station_result= mysqli_query($query);
$num= mysqli_fetch_array($station_result);
this is what I want to output, basically to pull every station name from the database called station_ord and the names are under station_name:
$i=0;while ($i < $num) {
$station_name1=mysqli_result($station_result,$i,"station1_name");
$station2_name= mysqli_result($station_result, $i,"station2_name");
$station3_name= mysqli_result($station_result, $i,"station3_name");
$station4_name= mysqli_result($station_result, $i,"station4_name");
$station5_name= mysqli_result($station_result, $i,"station5_name");
echo "<b>
$station1_name $station2_name2</b> <br>
$station3_name<br>
$station1_name4_name<br>
$station5_name<hr> <br>";
$i++;
}
I haven't put in the station_name yet as im confused to where and how I configure that.
Any ideas how to help?
Not sure what you try to do, but try
<?php
$station_result= mysqli_query($query);
$records = mysqli_fetch_array($station_result);
foreach ($records as $record) :?>
<b><?php echo $record['station_name']; ?></b><br/>
<?php endforeach; ?>
ref : http://ch1.php.net/manual/en/mysqli.query.php
and http://www.php.net/manual/en/mysqli-result.fetch-array.php for examples
Something like this should work.
$station_result= mysqli_query($query);
$results= mysqli_fetch_array($station_result);
foreach ($results as $row) {
// echo whatever you want here
echo $row['station_name'];
}
I get my dynamic navigation menu from the database because I have a CMS, so here's my code:
<ul>
<?php
$result = mysql_query("SELECT id, name, DESCRIPTION FROM menu where VISIBLE='1' ORDER BY `order` ASC") or die(mysql_error());
while($row = mysql_fetch_array($result)){
printf('<li>%s %s </a></li> ', $row['name'],$row['DESCRIPTION']);
}
?>
to highlight the current page, i have to add this inside the li element
how should i do this? Thanks in advance.
u can try the following code
<?php
$currentpage = $_SERVER['REQUEST_URI'];?>
<ul>
<?php
$result = mysql_query("SELECT id, name, DESCRIPTION FROM menu where VISIBLE='1' ORDER BY
`order` ASC") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
?>
<li<?php if(preg_match("/index/i", $currentpage)||($currentpage=="/")) { echo "
class='active'"; } ?>>Home</li>
<?
}
?>
instead of index you can also write $row[name] in a variable and replace /index/i with it
set a variable on the page like
$navlink = '<somevalue>'
and check the the value in li
<li <?php if($navlink == '<somevalue>') {echo "class='active'"}?>>
i think it will work.
I am having some problem in retrieving sub categories from mysql database.I want to display the sub-categeories for the parent categories.I am able to get only the last sub category of a main category. The first sub-categories are not displaying **. In my table **i have category_id and category_parent_id.where category_parent_id will be '0' for parent category. .Thanks in advance
<ul class="betterList">
<?php
$con = mysql_connect("localhost","root","pwd") or die('couldnot connect to database'.mysql_error());
mysql_select_db("DB",$con);
$result=mysql_query("select * from table ")or die("No table available with this name"."<br/><br/>".mysql_error());
while($row=mysql_fetch_array($result))
{
$parent_id=$row['category_parent_id'];
$category_id=$row['category_id'];
if($parent_id==0)
{
?>
<li>
<?php echo $row['category_id'].$row['name_en-GB'];
$result1=mysql_query("select * from table where category_parent_id=".$category_id)or die("No data available with this name"."<br/><br/>".mysql_error());
echo $num_row = mysql_num_rows($result1);
if($num_row>0) {
for($i=0;$i<$num_row;$i++)
{
while($row1=mysql_fetch_array($result1))
{
?>
<ul style="margin:0px;padding:0;">
<li><?php echo $row1['name_en-GB']?></li>
</ul>
<?php
}
}
}
?>
</li>
<?php } ?>
<?php }?>
</ul>
when i remove <li> tag which is at the end and keep it after at the end of in while i could display all the sub-catgeories but the css is not applying for that. Some thing is going wrong there but i couldn't figuer it out
Remove below and try again:
for($i=0;$i<$num_row;$i++)
{
Wow ! o_O
You're using old mysql_* functions ...
You wrote :
for($i=0;$i<$num_row;$i++)
And After :
while($row1=mysql_fetch_array($result1))
Both of these instructions are looping on each rows you got with this query.
Remove all of that:
echo $num_row = mysql_num_rows($result1);
if($num_row>0) {
for($i=0;$i<$num_row;$i++) {
Cause this is useless.
The only important thing to loop on your results is
while($row1=mysql_fetch_array($result1))
You can also replace mysql_fetch_array() by mysql_fetch_assoc() that is lighter.
Your code will be optimizable but this should solve your problem.
Instead of doing nested loops, get everything with a join:
SELECT t1.category_id parent, t1.`name_en-GB` parent_name,
t2.category_id child, t2.`name_en-GB` child_name
FROM table t1
JOIN table t2 ON t2.parent_category_id = t1.category_id
WHERE t1.parent_category_id = 0
Then your loop would be:
$last_parent = null;
$first_cat = true;
while ($row = mysql_fetch_assoc($result)) {
if ($row['parent'] != $last_parent) {
$last_parent = $row['parent'];
if (!$first_cat) { // Close out the last UL and LI
echo '</ul></li>';
} else {
$first_cat = false;
}
echo '<li>' . $row['parent'] . $row['parent_name'];
echo '<ul style="margin:0px;padding:0;">';
}
echo '<li>' . $row['child_name'] . </li>
}
if (!$first_cat) {
echo '</ul></li>';
}
You had too many nested loops in your code: you had both a for and while loop that were both trying to loop over the rows of the inner query. Also, you were putting each child into its own <ul>, which is probably not what you wanted.
Just try whether this solutions work for u, if it works adjust your code accordingly
$result = mysql_query("select * from table WHERE category_parent_id = 0 ");
while($row=mysql_fetch_array($result)) {
$parent_id = $row['category_parent_id'];
$query = mysql_query("select * from table where category_parent_id = {$parent_id}");
while($sub_cats=mysql_fetch_array($query)) {
echo '<pre>'.print_r($sub_cats).'</pre>';
}
}
just by adding internal <ul> before while loop i could get subcategories.
<?php
echo "<ul>";
while($row1=mysql_fetch_array($result1))
{
?>
<li><?php echo $row1['name_en-GB']?></li>
<?php
}
echo " </ul>";
Following on from a question earlier today this answer was given to read the data into an array and separate it to print vehicle type and then some data for each vehicle.
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
This is almost perfect for what I want to do but I need to print out two columns from the database ie ford and mondeo before going into the second foreach loop. I've tried print $rows['model'] and all the other combinations I can think of but that doesn't work. Any help much appreciated
I'm a bit confused by your question but the SELECT * in the SQL statement means that every column from the database should be present as a key=>value pair in the $row array. So if you needed another "column," output here into an HTML list element <li>, you just echo (note: not "print") that column name as an array key. So if you needed the type of the car column found in a column with the name "model" you'd do this:
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
EDIT: I'm still unclear on your question, but if every car has the same vehicleType, and you're just looking to grab that once before looping through all the results, I'm guessing this will do it:
<?php
// Set up a SQL query to grab one row
$query_to_grab_only_vehicle_type = "SELECT vehicleType FROM apparatus WHERE 1 LIMIT 0,1";
// Fetch that row and turn it into an array
$vehicle_type_array = mysql_fetch_array(mysql_query($query_to_grab_only_vehicle_type));
// Initialize a variable with the array value that came from the vehicleType column
$vehicle_type = $vehicle_type_array['vehicleType'];
// You could uncomment and use the following to echo out the variable
// echo "Vehicle type: $vehicle_type";
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>