So have the following while loop which will output all the results for a SQL query carried out in PHP:
while ($row = mysqli_fetch_array($result))
{
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
$output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
echo "$output";
}
You can assume that $result will contain the table which I am reading on row at a time. The above code is working just fine but when I try to display the information in HTML (so that it actually looks nice) I run into a problem
If I do the following:
<html>
<section id="main" class="container 75%">
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<?php echo $output; ?>
</div>
</section>
</html>
It will only display the very last resort. I know that this happening because $output can only hold one string at a time, but I don't know any other way to display the information on the HTML. I though of possibly using an array to store all the strings, but the documentation doesn't show me how to set-up a dynamic array.
Does anyone here know how to display all the results of the search query in an HTML page?
You can do combine both php and html code like this:
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<?php
while ($row = mysqli_fetch_array($result)) :
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
$output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
echo "<div class=\"box\">$output</div>";
endwhile;
?>
This way you don't have to use an array to display the result.
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<?php
while ($row = mysqli_fetch_array($result)) {
$row = mysqli_fetch_array($result);
echo 'Restaurant name: '.$row['restaurant_name'];
echo 'Cusine: '.$row['cusine'];
// ...and so on
}
?>
</div>
You can have the loop produce the HTML inside your div with a table. I am not sure what your CSS is like for your box class, but this will certainly make it look better while printing out all of your results.
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<table>
<tr>
<td>Restaurant</td>
<td>Cusine</td>
<td>Wait Time</td>
</tr>
while ($row = mysqli_fetch_array($result))
{
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
echo "<tr><td>". $restaurant_name . "</td><td>" . $cusine . "</td><td>" . $wait_time . "</td></tr>";
}
</table>
</div>
You are overwriting your $output variable every loop, and then trying to echo $output later; it will only contain the data from the last iteration.
Instead, make $output an array containing your data and then loop over it for display purposes:
$output=array();
while ($row = mysqli_fetch_array($result)) :
$output[]=$row;
endwhile
Then you can loop over the $output array to build an output for each restaurant:
foreach($output as $value):
$returnDetails='<div class="box">';
$returnDetails.='Resturant Name: '.$output['restaurant_name'].'<br />';
// etc. for all details
$returnDetails.='</div>';
echo $returnDetails;
endforeach;
Added benefit of this way: you have access to the $output array if you ever wanted to access a single row outside the context of the loop
Related
Hey I've recently been making a website and want to display the data from my database in a grid format opposed to it just listing down the page.
Here is my code right now:
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
I was wondering how I would go about creating a for loop to allow the data from this database in conjunction with the image to span across the page with 7 columns and however many rows down until it reaches the end of the database.
Thanks!
<?php
$query = "Select * from tablename";
$bind = $conn->query($query);
if ($bind->num_rows > 0){
while ($row = $bind->fetch_assoc()){
?>
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
<?php
}
}
?>
Try this, I just add while loop until End Of file (EOF table)
For parsing a list of articles, i have this code to parse all the articles:
while($article = $articles->fetch())
{
$date = strtotime($article['createdAt']);
$formatted_date = date("F Y",$date);
?>
<br />
<div class="news-content">
<div class="news-image">
<?php echo $article['title']; ?>
</div>
<div class="news-article">
<h3>
<span><?php $date = strtotime($article['createdAt']); echo /*date("F j",$date);*/ strftime('%e %B',$date) ?></span>
<br />
<?php echo $article['title']; ?>
</h3>
</div>
</div>
<?php
} //end while loop
?>
What i want to achieve: only the first 5 <div class="news-content">...</div> should be shown.
I know i have to do something with a for loop
but i do not know exactly how to use the for loop for this situation...
Can someone help me with that?
There are a lot of different ways to limit a loop. One possibility is to use a for loop instead of a while loop. for is often a good option if you want something to happen a specific number of times. Adding something else like fetch into the continuation condition will mean it happens up to a specific number of times.
for ($i = 0; $i < 5 && $article = $articles->fetch(); $i++) {
// output article
}
I am creating a search, and what I want is when the user searches they will be able to see a number of different attractions appear. At the minute when I search the data appears in a long list.
else {
while ($row = mysqli_fetch_array($result)) {
$attraction_name = $row['attraction_name'];
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$image = "<img src='{$row['image']}' height='100' width='100'>";
$output .= '<div>'.$attraction_name.' '.$lat.' '.$long.' '.$cost.' '.$image.'</div>';
}
}
I have added a simple html format which looks like the following
<div class="col-md-4">
<div class="thumbnail">
<?php print ("$output");?>
</div>
However the html appears all the time and I don't want this. What I would like is to create a search and then when the search results are returned they will appear in the html divs. Does anyone know how to do this? Thanks in advance.
You can wrap HTML in PHP logic like so:
<?php
if ($hasResults)
{ ?>
<div class="col-md-4">
<div class="thumbnail">
<?php print ("$output");?>
</div>
<?php }
?>
The following query returns all rows from the campaign table that have the user_id of 1:
SELECT * FROM campaign WHERE user_id=1
In the case of testing this is two results. How would I be able to echo a set column from each of the rows. For example, I want to echo the campaign_name from each of the results. I have tried various methods however, I have had no success.
My end goal would be something like this:
<?php foreach($queryRow as $row) { ?>
<li>
<a>
<div>
<p><?php echo($row['campaign_name']); ?></p>
<p>
Description Text
</p>
</div>
</a>
</li>
<?php } ?>
I'm quite at lost with this so I apologise if my intended result is completely off...
Try this:
$qry = "SELECT * FROM campaign WHERE user_id=1";
$res = mysqli_query($conn, $qry);
if(mysqli_num_rows($res) > 0) // checking if there is any row in the resultset
{
while($row = mysqli_fetch_assoc($res)) // Iterate for each rows
{
?>
<li>
<a>
<div>
<p><?php echo($row['campaign_name']); ?></p>
<p>
Description Text
</p>
</div>
</a>
</li>
<?php
}
}
It will iterate for each row in the resultset.
I looked into the documentation as Oldskool kindly suggested and realised I was using the wrong method to create an array. I instead use the fetch_all feature of the mysqli_results class to create a multidimensional array with my results. Then I was able to use the following code to echo out the results:
<!DOCTYPE html>
<html>
<body>
<?php
include('inc/database_initiation.php');
//print_r($userCampaigns);
foreach ($userCampaigns as $row) {
//echo $row[2];
//echo $row[4];
echo $row['campaign_name'];
echo '<br>';
echo $row['promotion_coins'];
echo '<br>';
}
?>
</body>
</html>
The include 'inc/database_initiation is as follows'
<?php
session_start();
include_once 'userManagement/dbconnect.php';
if(!isset($_SESSION['userSession']))
{
header("Location: login.php");
}
$query = $MySQLi_CON->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array();
$campaignQuery = $MySQLi_CON->query("SELECT * FROM campaign WHERE user_id=1");
$userCampaigns = $campaignQuery->fetch_all(MYSQLI_ASSOC);
//$MySQLi_CON->close();
?>
So the following code works, it is doing everything i want it to do. However, as i step back it seems like an overly convoluted approach to what is arguably one of the most common tasks in php.
I know enough about php to figure out what most things are doing when i see them, and to create some rather ugly code like you will see below; however, the finer points evade me.
I was hoping that if someone had some free time, he/she could look this over and show me a more concise way to approach this.
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<div id="item_gallery_s'.$i .'"'. 'class="fluid profileImgWrap goldDiagGrad">' .
'<div class="profile_name">' . $row['name'] . '<br /><span class="profile_date">' .
'<a href="http:#"
target="_blank"
title="some title">' . $row['place'] .
'</a></span></div><!-- DCD Diva Name -->' .
'<a rel="events[events]"
href="#">' .
'<div class="profile_banner">Custom Banner</div><!-- Banner -->' .
'<img src='.'"img/upload/'.$row['icon'].
'"' .
'alt="image description |'.$row['name'].
'"/>' .
'<!-- Photo --></a></div><!-- END #item_gallery_s'.$i .'-->';
$i++;
}?>
The loop itself is fine but you'll find varying opinions on the HTML-in-strings. For the past seven years I've encouraged my team to either use HTML with php tags or we rely on a full templating system:
<?php while ($row = mysql_fetch_assoc($result)): ?>
<div><?= $row['something'] ?></div>
<?php endwhile ?>
Though we have short tags enabled for even cleaner code. The benefit of this is that it's cleaner - less quotes, escaping problems, and IDEs will be able to syntax highlight the html. Most treat the html as string when it's inside quotes.
That's as "concise" as it gets.
You could not use an echo inside the while. And use php short tags.
while ($row = mysql_fetch_assoc($result)) {
?>
<?=$row['place'];?>
<?php
}
?>
Another way to "clean up", would be to use a template engine, but once again that would be just for the HTML part.
{place}
Good coding!
You can clean this up a bit by interspersing actual HTML, rather than simply echoing it:
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
?>
<div id="item_gallery_s<?php echo $i; ?>" class="fluid profileImgWrap goldDiagGrad">
<div class="profile_name">
<?php echo $row['name']; ?>
<br />
<span class="profile_date"><?php echo $row['place']; ?></span>
</div><!-- DCD Diva Name -->
<a rel="events[events]" href="#"><div class="profile_banner">Custom Banner</div><!-- Banner -->
<img src="img/upload/<?php echo $row['icon']; ?>" alt="image description |<?php echo $row['name']; ?>"/><!-- Photo --></a>
</div><!-- END #item_gallery_s<?php echo $i; ?> -->
<?php
$i++;
}?>
Another option, depending on how much work like this you have to do, would be a full-blown template engine such as Smarty.
Here's how I would probably format this code (as a matter of personal style):
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo
'<div id="item_gallery_s'.$i.'" class="fluid profileImgWrap goldDiagGrad">
<div class="profile_name">' . $row['name'] . '<br /><span class="profile_date">
<a href="http:#" target="_blank" title="some title">' . $row['place'] .
'</a></span>
</div><!-- DCD Diva Name -->
<a rel="events[events]" href="#">
<div class="profile_banner">Custom Banner</div><!-- Banner -->
<img src="img/upload/' . $row['icon']. '"
alt="image description |' . $row['name']. '"/>
<!-- Photo -->
</a>
</div><!-- END #item_gallery_s'.$i .'-->';
$i++;
}
?>
Try also to use consistent indentation to make it easy to tell what matches up with what. By the way, a <div> (block element) inside an <a> (inline element) is bad form. Did you mean to use a <span>? Learn to use the W3C validator to pick up this stuff.