this script outputs the birthdays as headlines and the customer(s) below.
So the output is "grouped" by the date of birth.
echo "<div>";
foreach(pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty)) as $row)
{
if(!isset($birthday) or $birthday != $row['birthday'])
{
unset($drawline);
echo "</div>";
echo "<div class=title><h1>".$row['birthday']."</h1></div><div class=customer>";
}
if(isset($drawline)){echo "<hr>";}
echo $row['customer']."<br>";
$drawline = 1;
$birthday = $row['birthday'];
}
echo "</div>";
'birthday' is a DATE-field in the database.
Between the customers there's always a line (hr), but not after the last customer of a d.o.b.
Example output:
<div class=title><h1>1986-10-08</h1></div>
<div class=customer>
Don Foo<br>
<hr>
Joe Bar<br>
</div>
<div class=title><h1>1988-03-18</h1></div>
<div class=customer>
Jane Fonda<br>
<hr>
Elvis Burns<br>
</div>
Is it possible to remove the <div> and </div> outside the foreach()?
It produces always an empty <div></div>.
I've decided that it's too much hassle on the programmer's mind to see what's happening here, so here is much cleaner version of your code.
<?php
$people = pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty));
if (!empty($people)) {
// Find out people with the same birthday and group them.
$birthdays = [];
foreach ($people as $man) {
$birthday = $man['birthday'];
if (empty($birthdays[$birthday])) {
$birthdays[$birthday] = [];
}
$birthdays[$birthday][] = $man['customer'];
}
// Now let's output everything!
?>
<div>
<?php foreach ($birthdays as $birthday => $customers): ?>
<div class=title><h1><?= $birthday ?></h1></div>
<div class="customer">
<?= implode('<br><hr>', $customers) ?>
</div>
<?php endforeach;?>
</div>
<?php } // endif (!empty($people)) ?>
Main point of this solution - very simple to understand, uses somewhat templating (you could create one for this little snippet), easy to debug and modify. And yes, it does not output the empty <div></div> anymore!
Related
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 want to only display an item once in my PHP loop. So if there's multiple values which are the same in $item['name'], it should only display it 1 time.
This is my loop:
<?php
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<li>
<i class="fa fa-archive"></i>
<h5><?php echo $item['name']; ?></h5>
<h3><?php echo $item['displayname']; ?></h3>
Download
<div class="clearfix"></div>
</li>
<?php
}
?>
But I have no idea how I would hide the other items with the same name. I also can't find any info about this on Google (or I'm using the wrong search terms?). Hope someone got a suggestion for me!
$array=array();
foreach ($item['name'] as $i) {
if (!in_array($i, $array)) {
$array[] = $i;
}
}
print_r($array);
<?php
// Produce your prepared statement $stmt here...
// The list of unique item names.
$itemNames = array();
// The list of items to be displayed on screen.
$displayItems = array();
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {
$itemName = $item['name'];
if (!in_array($itemName, $itemNames)) { // If item name not already appended to the unique names list.
// Append item name to the unique names list.
$itemNames[] = $itemName;
// Append item to the list of displayable items.
$displayItems[] = $item;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<!-- Css/Js resources -->
</head>
<body>
<ul id="items">
<?php
foreach ($displayItems as $item) {
$name = $item['name'];
$displayName = $item['displayname'];
$downloadUrl = $item['downloadurl'];
?>
<li>
<i class="fa fa-archive"></i>
<h5>
<?php echo $name; ?>
</h5>
<h3>
<?php echo $displayName; ?>
</h3>
<a href="<?php echo $downloadUrl; ?>" class="btn btn-default pull-right">
Download
</a>
<div class="clearfix"></div>
</li>
<?php
}
?>
</ul>
</body>
</html>
Note:
I always maintain the code responsible for db data access on the upper part of the page. So, for example, if I need to fetch data from db, I save it into arrays. Later, in order to bring that data in html constructs, I work just with them, without having to mix data access commands like
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {...}
with html code. Therefore gaining (highly) increased code readability. When you create a lot of files in this way, the advantages will become obvious.
There are also (rare) disadvantages though, like the one arised here: in order to avoid mixing the db codes with the html code, I had to apply an extra array iteration: the one for building the $displayItems array.
Otherwise, if you want to use your approach, then the solution would be:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<!-- Css/Js resources -->
</head>
<body>
<ul id="items">
<?php
// Produce your prepared statement $stmt here...
// The list of unique item names.
$itemNames = array();
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {
$name = $item['name'];
if (!in_array($name, $itemNames)) { // If item name not already appended to the unique names list.
// Append item name to the unique names list.
$itemNames[] = $name;
$displayName = $item['displayname'];
$downloadUrl = $item['downloadurl'];
?>
<li>
<i class="fa fa-archive"></i>
<h5>
<?php echo $name; ?>
</h5>
<h3>
<?php echo $displayName; ?>
</h3>
<a href="<?php echo $downloadUrl; ?>" class="btn btn-default pull-right">
Download
</a>
<div class="clearfix"></div>
</li>
<?php
}
}
?>
</ul>
</body>
</html>
Good luck.
Are you trying to do something like this? If I am understanding correctly, I think you are trying to do the same thing I was.
Other people gave you good solutions to solve your issue, but this thing is going to cost you more processing time through your app run-time.
You can use DISTINCT keyword in your sql select query so automatically you will get the name just once.
Chick this tutorial:
https://www.w3schools.com/sql/sql_distinct.asp
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
I want to print the div with the class called inner-content-div, if the variable $name is not consisted with the following strings.
Gingelly Rolls
Kithul Treacle
Coconut Vinegar
But my PHP code is not working.
Here is my code.
<?php
$vid = explode("/", $_GET["q"]);
$name = taxonomy_term_load($vid[2]);
?>
<h1 id="page-title" class="title"><?php print $name->name; ?></h1>
<?php
$exclude_list = array("Gingelly Rolls","Kithul Treacle","Coconut Vinegar");
if(!in_array($name, $exclude_list)){ ?>
<div class="inner-content-div">
<!-- Here are some HTML code.-->
</div>
<?php
}
?>
It should be -
if(!in_array($name->name, $exclude_list)){
as you are printing it -
<h1 id="page-title" class="title"><?php print $name->name; ?></h1>
<?php
$vid = explode("/", $_GET["q"]);
$name = taxonomy_term_load($vid[2]);
$exclude_list = array("Gingelly Rolls","Kithul Treacle","Coconut Vinegar");
?>
<h1 id="page-title" class="title"><?php echo $name->name; ?></h1>
<?php if(!in_array($name->name, $exclude_list)): ?>
<div class="inner-content-div">
<!-- Here are some HTML code.-->
</div>
<?php endif; ?>
It could be because $name is an object. Also, probably better to use PHP's alternate syntax for cleaner html/templates.
The other potential issue here is that the casing of the items in the exclude list could potentially not match the value of name. You should probably normalize those to all lower case when doing the comparison.
you can try like this. First print $vid[2], using echo $vid[2];. Then put $vid[2] values into the array called $exclude_list. Then use the following code.
$exclude_list = array(//value 1, value 2, value 3);
if(!in_array($vid[2], $exclude_list)) {
//Your HTML code
}
I am a newbie to PHP but trying to learn it to enhance my programming skillset
So far i have the following PHP code in my page to return some data from my Database:
<?php
//code missing to retrieve my data
while($row = mysql_fetch_array($result))
{
echo '$row['Name']';
}
mysql_close($connection);
?>
This is working in that I can see the names from my database displayed on screen. I have seen as well that I can include html in the echo to format the data. However if I have the html code like below in a jQuery accordion outside my PHP code in the page - how can I dynamically place the Names in the specific h3 tags - so the first name in my table is Joe so that comes back in [0] element of array - is there a way I can reference this from my html code outside the php?
<div id="accordion">
<h3>Joe</h3>
<div>
<p>
Some blurb about Joe
</p>
</div>
<h3>Jane</h3>
<div>
<p>
Some blurb about Jane
</p>
</div>
<h3>John</h3>
<div>
<p>
Some Blurb about John.
</p>
</div>
</div>
Try something like this:
<?php while($row = mysql_fetch_array($result)) { ?>
<h3><?php echo $row['name']; ?></h3>
<div>
<p>Some blurb about Joe</p>
</div>
<?php } ?>
I'm assuming 'Some blurb about Joe' would also have to be replaced by a field in the DB, which you can accomplish in the same manner as the name.
#Gert is correct - the original mysql API is deprecated and should not be used anymore. Look into mysqli or PDO, instead.
add your html in while loop like this
<?php
//code missing to retrieve my data
while($row = mysql_fetch_array($result))
{
?>
<h3><?php echo $row['Name']?></h3>
<div>
<p>
Some blurb about <?php echo $row['Name']?>
</p>
</div>
<?php
}
mysql_close($connection);
?>
Like this :
<div id="accordion">
<?php
while($row = mysql_fetch_array($result))
{
<h3><?php echo $row['Name'] ?></h3>
<div>
<p>
Some blurb about Joe
</p>
</div>
} ?>
</div>