I am running a while loop to return all the results of a mysqli query but I want to use php to group the results.
My code is
while($row = mysqli_fetch_array($result))
{
if($row['total'] >0)//row['total'] is found out within the query itself
{
$recipeWords = str_word_count(preg_replace('/\s{1,}(and\s*)*/', ' ', $row['title']));
if($countTerms == $recipeWords)
{
echo "<h2>Exact Match</h2>";?>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id=<?php echo $row['recipeID']?>">
<img src="images/recipes/<?php echo $row['image']?>" alt="<?php echo $row['title']?>" title="<?php echo $row['title']?>" />
<h4><?php echo $row['title']?></h4></a>
</div><?php
}
elseif($countTerms == ($recipeWords-1))
{
echo "<h2>Closest Matches</h2>";?>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id=<?php echo $row['recipeID']?>">
<img src="images/recipes/<?php echo $row['image']?>" alt="<?php echo $row['title']?>" title="<?php echo $row['title']?>" />
<h4><?php echo $row['title']?></h4></a>
</div><?php
}
else
{
echo "<h2>Other Suggestions</h2>";?>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id=<?php echo $row['recipeID']?>">
<img src="images/recipes/<?php echo $row['image']?>" alt="<?php echo $row['title']?>" title="<?php echo $row['title']?>" />
<h4><?php echo $row['title']?></h4></a>
</div><?php
}
}
}?>
What I am trying to do is group the results so that:
all the exact matches are displayed first
then I want all the records where all but one of the keywords are found
then the rest
at the moment they are being displayed on what seems a random order.
<?php
while($row = mysqli_fetch_array($result))
{
if($row['total'] >0)//row['total'] is found out within the query itself
{
$recipeWords = str_word_count(preg_replace('/\s{1,}(and\s*)*/', ' ', $row['title']));
$exactMatches = "";
$closestMatches = "";
$otherSuggestions = "";
if($countTerms == $recipeWords)
{
$exactMatches .= <<<EXACT_MATCH
<h2>Exact Match</h2>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id={$row['recipeID']}">
<img src="images/recipes/{$row['image']}" alt="{$row['title']}" title="{$row['title']}" />
<h4>{$row['title']}</h4></a>
</div>
EXACT_MATCH;
}
elseif($countTerms == ($recipeWords-1))
{
$closestMatches .= <<<CLOSEST_MATCH
<h2>Closest Match</h2>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id={$row['recipeID']}">
<img src="images/recipes/{$row['image']}" alt="{$row['title']}" title="{$row['title']}" />
<h4>{$row['title']}</h4></a>
</div>
CLOSEST_MATCH;
}
else
{
$otherSuggestions .= <<<OTHER_SUGGESTIONS
<h2>Other Suggestions</h2>
<div class="fluid recipeContainerSmall">
<a href="recipe_details.php?id={$row['recipeID']}">
<img src="images/recipes/{$row['image']}" alt="{$row['title']}" title="{$row['title']}" />
<h4>{$row['title']}</h4></a>
</div>
OTHER_SUGGESTIONS;
}
// ECHO in the order you want to...
echo $exactMatches . $closestMatches . $otherSuggestions;
}
}?>
As asked by you above, please try this code.
Please note that I've used HEREDOCS to simplify the parsing of the data.
Related
I have a problem looping my html tags. My goal is to enclose every 4 div with class "item" inside the class of "item-wrap". So far here's my code:
$speakers will return 8 rows so "item-wrap" class will be display twice with 4 "item" class inside
<?php
$speaker_ctr = 0;
if(count($speakers) > 0){
?>
<div class="item-wrap">
<?php foreach($speakers as $speaker){ ?>
<div class="item"> <img class="lazy" data-lazy-src="<?php echo $speaker['imagepath']; ?>" />
<h5 class="txt-18 bold-font text-uppercase no-mbt mt-20"><?php echo $speaker['name']; ?></h3>
<p class="no-mn"><?php echo $speaker['position']; ?></p>
<?php echo $speaker['company']; ?>
</div>
<?php } ?>
</div>
<?php
$speaker_ctr++;
}
?>
Try below code:-
<?php
if(count($speakers) > 0){
for($i=0;$i<=count($speakers);$i++){
if($i%4==0){
echo '<div class="item-wrap">';
}
?>
<div class="item"> <img class="lazy" data-lazy-src="<?php echo $speakers[$i]['imagepath']; ?>" />
<h5 class="txt-18 bold-font text-uppercase no-mbt mt-20"><?php echo $speakers[$i]['name']; ?></h3>
<p class="no-mn"><?php echo $speakers[$i]['position']; ?></p>
<?php echo $speakers[$i]['company']; ?>
</div>
<?php
if($i%4==0){
echo '</div>';
}
}
}
Try with -
$speaker_ctr = 0;
if(count($speakers) > 0){
?>
<div class="item-wrap">
<?php
foreach($speakers as $speaker){
$speaker_ctr++; // increment
?>
<div class="item"> <img class="lazy" data-lazy-src="<?php echo $speaker['imagepath']; ?>" />
<h5 class="txt-18 bold-font text-uppercase no-mbt mt-20"><?php echo $speaker['name']; ?></h3>
<p class="no-mn"><?php echo $speaker['position']; ?></p>
<?php echo $speaker['company']; ?>
</div>
<?php
// print if divisible by 4
// every 4th element
if($speaker_ctr%4 == 0 && $speaker_ctr != count($speakers)) {
echo "</div><div class='item-wrap'>";
}
}
?>
</div>
<?php
}
I have this most annoying problem; I'm trying to arrange three divs on a row, and then new row, and another three divs and so on, like this:
<div class="container">
<div class="row">
<div class="col-sm-1">1</div>
<div class="col-sm-1">2</div>
<div class="col-sm-1">3</div>
</div>
<div class="row">
<div class="col-sm-1">4</div>
<div class="col-sm-1">5</div>
<div class="col-sm-1">6</div>
</div>
</div>
As for this accepted answer,
There is one catch: 0 % 3 is equal to 0. This could result in
unexpected results if your counter starts at 0.
So how would i implement this into this code:
<div class="col-md-8">
<?php
foreach($this->movies->movie_data as $key => $movie){
$string = file_get_contents("http://example.com/?t=" . urlencode($movie->movie_titel). "&y=&plot=short&r=json");
$result = json_decode($string);
if($result->Response == 'True'){
?>
<div class="col-sm-4">
<?php if($result->Poster == 'N/A') : ?>
<a href="<?php echo Config::get('URL')?>ladybug/day/<?php echo $this->city ?>/<?php echo $movie->movie_id ?>">
<img src="<?php echo Config::get('URL')?>/images/na.png" class="img-responsive img-thumbnail"></a>
<?php else: ?>
<a href="<?php echo Config::get('URL')?>ladybug/day/<?php echo $this->city ?>/<?php echo $movie->movie_id ?>">
<img src="<?php echo $result->Poster; ?>" class="img-responsive img-thumbnail"></a>
<?php endif; ?>
<div><b><?php echo $result->Title; ?></b></div>
<div><i><?php // echo $result->Plot; ?></i></div>
</div>
<?php }else{ ?>
<div class="col-sm-4">
<a href="<?php echo Config::get('URL')?>ladybug/day/<?php echo $this->city ?>/<?php echo $movie->movie_id ?>">
<img src="<?php echo Config::get('URL')?>/images/na.png" class="img-responsive img-thumbnail"></a>
<div><b><?php echo $movie->movie_titel ?></b></div>
<div class="plot"><i><?php //echo 'N/A' ?></i></div>
</div>
<?php }}} ?
</div>
For some reason, divs is arranged like this:
My question: How do I arrange thumbnails on a new row, every third time?
Found the answer in the other Q... Didn't read, sorry about that.
<?php }
if (($key + 1) % 3 == 0) { ?>
</div>
<?php }
}} ?>
I am creating a property website from a database with PHP. On the description of each property listed has a slider of up to 10 images/slides. However, if there are only 6 images/slides for example; i would like to hide the remaining 6 images/slides from showing.
Here is what i have so far;
$sql = DB::getInstance()->query('SELECT * FROM listings WHERE id =' . Input::get('id'));
foreach($sql->results() as $row) {
<div id="property-slider">
<section class="slider">
<div class="flexslider">
<ul class="slides">
<li>
<figure>
<img src="admin/<?php echo $row->img_set_1 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_2 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_3 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_5 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_6 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_7 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_8 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_9 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
<li>
<figure>
<img src="admin/<?php echo $row->img_set_10 ?>" alt="<?php echo $row->alt ?>">
</figure>
</li>
</ul>
</div>
</section>
</div>
}
I am trying to get a result simular to this, but think repeating this 10 time etc etc, just think there is a better way
<?php
if(empty($row->img_set_1)) {
echo "";
} else {
echo "<li>";
echo "<figure>";
echo "<a href='#'><img src='{admin/$row->img_set_1}'></a>";
echo "</figure>";
echo "</li>";
}
?>
this is the function for the query
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
THIS IS AN UPDATE OF THE WORKING SLIDER---NOT IDEAL BUT IT WORKS
<?php
if(empty($row->img_set_1)) {
echo "";
} else {
echo "<li>";
echo "<figure>";
echo "<a href='#'><img src='admin/{$row->img_set_1}'></a>";
echo "</figure>";
echo "</li>";
}
if(empty($row->img_set_2)) {
echo "";
} else {
echo "<li>";
echo "<figure>";
echo "<a href='#'><img src='admin/{$row->img_set_2}'></a>";
echo "</figure>";
echo "</li>";
}
//This repeats etc etc
?>
You could do something like this:
$x = 1;
while($x<=10) {
if(!empty($row["img_set_$x"])) {
echo "<li>";
echo "<figure>";
echo "<a href='#'><img src=".'{admin/'.$row["img_set_$x"].'}'."</a>";
echo "</figure>";
echo "</li>";
}
$x++;
}
I have a question that bothers me for a long time. Lets say i have a code with several nested div's and span's. All these compose a square with an image inside.
echo '<div> <div> <div> <div> <span> <img src='.$image.'> </span></div></div></div>';
Only that this code has about 15 rows.
From what i know when echo-ing the results from db in that form i put in the loop the whole html code. It looks clumsy this way.
It is there a better practice ?
foreach ($query->result() as $row)
{
$row->address_link=strtolower($row->network);
echo '<li class="col-md-3 isotope-item '.$row->network.'">';
echo '<div class="portfolio-item img-thumbnail">';
echo '<table border="0"><tr>';
echo '<a href="order/'.$row->address_link.'/'.$row->value.'" class="thumb-info">';
echo '<img alt="" class="img-responsive" src="img/'.$row->address_link.'.png">';
echo '<span class="thumb-info-title">';
echo '<span class="thumb-info-inner">'.$row->value.' Euro</span>';
echo '</span>';
echo '<span class="thumb-info-action">';
echo '<span title="Universal" href="order/'.$row->address_link.'/'.$row->value.'" class="thumb-info-action-icon"><i class="icon icon-link"></i></span>';
echo '</span>';
echo '</a>';
echo '</div>';
echo '</tr><tr>';
echo '<span class="thumb-info-type">'.$row->value*$row->rate.' Eur</span>';
echo '</tr></table>';
echo '</li>';
}
If you are new to php you can define a function for this:
function wrapImage($src){
return '<div> <div> <div> <div> <span> <img src='.$src.'> </span></div></div></div>';
}
And just use echo wrapImage($src) where you need it with different params.
EDIT: consider following way of presenting the data:
<?php
$query = 'select * from Unicorns';
foreach ($query->result() as $row){
$row->address_link=strtolower($row->network);
?>
<!-- html -->
<li class="col-md-3 isotope-item <?php echo $row->network; ?>">
<div class="portfolio-item img-thumbnail">
<table border="0"><tr>
<a href="order/<?php echo $row->address_link.'/'.$row->value; ?>" class="thumb-info">
<img alt="" class="img-responsive" src="img/'.$row->address_link.'.png">
<span class="thumb-info-title">
<span class="thumb-info-inner"><?php echo $row->value; ?> Euro</span>
</span>
<span class="thumb-info-action">
<span title="Universal" href="order/<?php echo $row->address_link.'/'.$row->value ?>" class="thumb-info-action-icon"><i class="icon icon-link"></i></span>
</span>
</a>
</div>
</tr><tr>
<span class="thumb-info-type"><?php echo ($row->value*$row->rate); ?> Eur</span>
</tr></table>
</li>
<!-- /html -->
<?php } ?>
It is called spaghetti code .. and it is NOT the best practice but is better then your example in case the HTML is more then the PHP data.
first of all, dont use echo in loops (optimalization), store your output in variable and print it only once.
Repeated code can be stored inside function
function square($image){
return '<div> <div> <div> <div> <span> <img src='.$image.'> </span></div></div></div>';
}
$output = '';
while ($loop){
$output .= square($image);
}
echo $output
I wanted to display all of my shirts but I always get the same error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/36/d362778419/htdocs/home/specials.php on line 34
Here is the code I have currently in place
<?php
require "connect2.php";
$sql = mysql_query("SELECT * FROM shirts WHERE all='1'");
$runrows = mysql_fetch_array($sql);
$title = $runrows['title'];
$picture = $runrows['picture'];
$newp = $runrows['newp'];
$date = strftime("%b %d, %Y %l:%M %p" ,strtotime($runrows['date']));
$oldp=$runrows['oldp'];
$viewl=$runrows['viewl'];
$shirtl = $runrows['shirtl'];
echo "";
?>
<div class="specialsListBoxContents centeredContent back" style="width:25%;"><div class="product-col" > <div class="img">
<a href="detail.php?id=<?php echo $id; ?>"><img src="<?php echo $picture; ?>" alt="<?php echo $title; ?>" title=" <?php echo $title; ?> " width="190"
height="160" /></a> </div> <div class="prod-info"> <div class="wrapper">
<div class="price"> <strong><span class="normalprice"><?php echo $oldp; ?
></span><br /><span class="productSpecialPrice"><?php echo $newp; ?></span></strong> </div>
<div class="button"><a href="detail.php?id=<?php echo $id; ?>"><img src="images/button_add_to_cart.gif" alt="Add to Cart" title=" Add to Cart " width="54"
height="49" /></a></div> </div> </div> </div></div>
<?php
?>
mysql_*() functions return boolean FALSE if they fail, which means your query call did not succeed. Add this code to find out the reason why:
$sql = mysql_query("SELECT * FROM shirts WHERE all='1'");
if ($sql === FALSE) {
die(mysql_error());
}
Here's some sample code:
<?php
$sql = mysql_query("SELECT * FROM shirts WHERE `all`='1'");
if (!$sql ) {
echo "Could not successfully run query from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($sql) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
while ($row = mysql_fetch_assoc($sql))
{
?>
<a href="detail.php?id=<?php echo $row['id']; ?>"><img src="<?php echo $row['picture']; ?>" alt="<?php echo echo $row['title']; ?>" title=" <?php echo $row['title']; ?> " width="190" height="160" />
<?php
}
?>
And here is more info. Notice the exiting php mode inside the while.