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 ?>
Related
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
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 have a slight problem here. I have the following code that I create a search query, and im trying to take "$row" array and create a new array called "$item" so I can echo the values inside my div statement. This code works, and I do echo the $item array with the 'follower_username' values, however only the last value gets echoed out. I have values inside my database Nathan, Brett, Nathan2 and it only echoes Nathan2, or the last value of the array $item.
Here is my code:
$result = mysqli_query($con,"SELECT * FROM followers
WHERE username='$username'");
?>
<?php
while ($row = mysqli_fetch_array($result))
{
$item = $row;
}
?>
<body>
<div id="contentwrap">
<div rel="scrollcontent2">
<?php echo $item['follower_username'];?> <img style="width: 50px; height: auto;"<?php echo '<img src="/user_photo/' . $item['follower_username'] . '.jpeg" />';?>
</div>
I hope I can get this resolved, it is bugging me! Thank you for any help!!
What you're doing is reassigning the value of item to the current row each time.
$row will be an object of table row values from the resulting query so if you want all the rows in an $item variable that would need to be an array to store each result, instead of storing the current row in the same variable for each row.
You will then need to iterate that array to display each result.
$i = 0;
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[$i] = $row;
$i++;
}
<div>
<?php
foreach ($item as $value)
{
echo $value['follower_username'];
}
?>
</div>
Below is an example to show some shorthand versions of the same idea:
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[] = $row;
}
<div>
<ul>
<?php foreach ($item as $value): ?>
<li><?php echo $value['follower_username']; ?></li>
<?php endforeach; ?>
</ul>
</div>
while ($row = mysqli_fetch_array($result))
What that does is grab the next row in the result set, and assign it to the variable $row. Each time the loop runs, it assigns the latest row to $item. So to store the whole result set, use
$item[] = $row.
I'm sure what you are trying to accomplish with our next line of code. To show all items you need something like
foreach($item as $singleItem)
{
echo $singleItem['follower_username']."<br>";
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to rewrite this script using PDO:
Get values from the database
mysql_select_db($database_db_FPF, $db_FPF);
$query_rsWorksMenu = "SELECT works.year, GROUP_CONCAT(workstitle.title) as titulos, GROUP_CONCAT(workstitle.id_title) as links FROM works JOIN workstitle ON works.id_year = workstitle.id_year GROUP BY works.year ORDER BY works.year DESC";
$rsWorksMenu = mysql_query($query_rsWorksMenu, $db_FPF) or die(mysql_error());
$row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu);
Show values
<ul>
<?php do { ?>
<li><span><?php echo $row_rsWorksMenu['year']; ?></span>
<ul>
<?php
$titulos = explode(",", $row_rsWorksMenu['titulos']);
$links = explode(",", $row_rsWorksMenu['links']);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><?php echo $titulo; ?></span></li>
<?php } ?>
</ul>
</li>
<?php }while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu)); ?>
</ul>
What I got so far:
Get the values from the database:
$stmt2 = $conn->prepare('SELECT works.year, GROUP_CONCAT(workstitle.title) as titulos, GROUP_CONCAT(workstitle.id_title) as links FROM works JOIN workstitle ON works.id_year = workstitle.id_year GROUP BY works.year ORDER BY works.year DESC');
$stmt2->execute();
$result2 = $stmt2->setFetchMode(PDO::FETCH_OBJ);
Show values
<ul>
<?php do { ?>
<li><span><?php echo $result2->year; ?></span>
<ul>
<?php
$titulos = explode(",", $result2->titulos);
$links = explode(",", $result2->links);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><?php echo $titulo; ?></span></li>
<?php } ?>
</ul>
</li>
<?php }while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu)); ?>
</ul>
The problem is that I don't know what to do with this line:
}while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu));
UPDATE:
I change my code:
$stmt2 = $conn->prepare('...query...');
$stmt2->execute();
$result2 = $stmt2->fetchAll();
}while ($row_rsWorksMenu = $stmt2->fetchAll());
But nothing happens.
UPDATE 2
I try this code:
<?php do { ?>
<li><span><?php echo $result2->year; ?></span>
<ul>
<?php
$titulos = explode(",", $result2->titulos);
$links = explode(",", $result2->links);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><?php echo $titulo; ?></span></li>
<?php } ?>
</ul>
</li>
<?php }while($result2 = $stmt2->fetch()); ?>
And my DOM show the correct numbers of <li>. But no values. Why?
The easiest way would be something like this:
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
The PDO query method returns a PDOStatement which you can iterate directly.
http://www.php.net/manual/de/pdo.query.php
Drop your while loop completely. You also don't need to prepare a statement separately since your query doesn't use any query parameters.
Do this instead:
// Get all your DB results in one place
$rsWorksMenu = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
And later, to display the results:
<?php if ($rsWorksMenu):?>
<ul>
<?php foreach($rsWorksMenu as $r):
$links_titulos = array_combine(
explode(",", $r->titulos),
explode(",", $r->links)
);
?>
<li><span><?=h($r->year)?></span>
<?php if ($links_titulos):?>
<ul>
<?php foreach($links_titulos as $link => $titulo):?>
<li><span><a href="works.php?id=<?=h(urlencode($link))?>"><?=h($titulo)?>a></span></li>
<?php endforeach // $links_titulos?>
</ul>
<?php endif //$links_titulos?>
</li>
<?php endforeach // $rsWorksMenu?>
</ul>
<?php endif // $rsWorksMenu?>
You should change your sql statement also--it will break if any of your links or titles have commas in them. (GROUP_CONCAT is generally a bad idea).
Instead, collect the ungrouped values and group them in a php array yourself, as in the get_worksmenu function below:
<?php
function get_worksmenu(PDO $db) {
$rsWorksMenu = array();
$sql = 'SELECT works.year, workstitle.title AS titulos, workstitle.id_title AS links '
.'FROM works INNER JOIN workstitle USING (id_year) ORDER BY year DESC';
// Could this be a single-table query instead?
// SELECT id_year AS year, title AS titulos, id_title AS links
// FROM workstitle ORDER BY id_year DESC
$rs = $db->query($sql);
$rs->setFetchMode(PDO::FETCH_ASSOC);
foreach ($rs as $r) {
// calculating url here simplifies your display code
// and makes it easy to change urls later
$year = $r['year'];
$r['url'] = '/works.php?id='.urlencode($r['links']);
unset($r['year']);
$result[$year][] = $r;
}
$rs->closeCursor();
return $rsWorksMenu;
}
function h($s) {
// escape a string for html
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
$rsWorksMenu = get_worksmenu($conn);
<?php if ($rsWorksMenu):?>
<ul>
<?php foreach($rsWorksMenu as $year => $works):?>
<li><span><?=h($year)?></span>
<ul>
<?php foreach($works as $work):?>
<li><span><?=h($work['titulos'])?></span></li>
<?php endforeach //$work?>
</ul>
<?php
</li>
<?php endforeach // $rsWorksMenu?>
</ul>
<?php endif // $rsWorksMenu?>
I am a little stuck on how to create this array.
My data:
category_id | category_name
1 bikes
2 cars
3 books
4 computers
Array:
$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
$category_id=$row['category_id'];
$category_name=$row['name'];
}
I want to create an array so that I can echo the data in a radio list like...
<input type='radio' value='<?PHP echo $category['category_id']; ?>'
name='category[]'><?PHP echo $category['category_name']; ?>
o bikes
o cars
o books
o computers
The problem is that the array only consists of one pair (1, bikes) and not all the data.
How can I make an array with all the data?
Thanks!
You are doing three things wrong, first you are not actually setting $category to equal anything - only the values of two undefined values, which default to null. So you end up with an array like:
array('category_id' => null, 'name' => null)
Second, you are doing nothing with the values of $category_id and $category_name when you do set them. Next, you are not going through the array item by item, you simply output the initial way it was set - which is linked to another problem that your array is short of a dimension. It should be 2-dimensional, not 1-dimensional.
This code sums up the gist of it all. I would suggest reading up on how arrays work in PHP and how to define them, they're a very commonly used data type throughout frameworks and the like.
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$categories=array();
while ($row = $result->fetch_array()){
$categories[] = array('category_id' => $row['category_id'], 'category_name' => $row['name']);
}
Then when you need to output:
foreach ( $categories as $category ) {
?>
<input type='radio' value='<?php echo $category['category_id']; ?>' name='category[]'><?php echo $category['category_name']; ?>
<?php
}
This can of course be cleaned up further.
That is because you are echoing out side of the loop there by giving you only first row records eg bikes, you should do like:
$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
$category_id=$row['category_id'];
$category_name=$row['name'];
?>
<input type='radio' value='<?PHP echo $category['category_id']; ?>'
name='category[]'><?PHP echo $category['category_name']; ?>
<?php
}
You are assigning to variables $category_id and $category_name, rather than to the array $category, so you're only seeing the first row returned from the query.
I normally use PDO, and would write it something like this:
<?php
$db = ...
$sql = 'SELECT * FROM categories ORDER BY category_name ASC';
$categories = $db->query($sql);
?>
<html>
<body>
<? foreach ($categories as $category): ?>
<input type="radio" name="category[]" value="<?= $category->category_id ?>">
<?= $category->category_name ?>
</input>
<? endforeach ?>
</body>
</html>