Best practice when echo repeated code - php

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

Related

Getting images from RSS using PHP

I want to display an RSS feed on a web page. Currently I'm only getting the title and description but I want to get images also.
<?php
$html = "";
$url = "http://rss.cnn.com/rss/edition.rss";
$xml = simplexml_load_file($url);
foreach ($xml->channel->item as $itm) {
$title=$itm->title;
$link=$itm->link;
$pubDate=$itm->pubDate;
$description=$itm->description;
$img=$itm->media;
}
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php echo $title; ?><br>
<span class="text text-info"><?php echo $pubDate; ?></span><br>
<p align="right" class="text text-info"><?php echo $description; ?></p>
<img src="<?php echo $img; ?>"></img>
</div>
</div>
</div>
<?php } ?>
You've finished your foreach loop twice. That's almost certainly not what you want to happen, or you wouldn't have used the foreach loop.
Try removing the first } (before the bulk of the HTML) and also replacing <img src="<?php echo $img; ?>"></img> with <img src="<?php echo $img; ?>" />.

Html link <a> not wrapping <div> element properly

I am currently writing a php website where I encountered a problem where the html link will not wrap div element properly. I have not found an answer to my problem yet, so I appreciate if someone can help me.
This is the php code I had written:
ECHO '<a target="_blank" href="' . $row["link"] . '">';
ECHO '<div class="header-box">';
ECHO '<div class="detail">';
ECHO '<p class="title">' . $row["title"] . '</p>';
$user_data = get_user_data($row["owner_id"]);
ECHO '<p class="author">This article is shared by <a class="user" href="./member.php?action=profile&id='.$user_data["id"].'">' . $user_data["firstname"] . " " . $user_data["lastname"] . '</a> on '.date("d F Y", strtotime($row["posted"])).'.</p>';
ECHO '</div>';
ECHO '<div class="good">';
ECHO '<p id="number">'.$row["good"].'</p>';
ECHO '<p id="icon"><i class="fa fa-thumbs-o-up"></i>Useful</p>';
ECHO '</div>';
ECHO '<div class="bad">';
ECHO '<p id="number">'.$row["bad"].'</p>';
ECHO '<p id="icon"><i class="fa fa-thumbs-o-down"></i>Not Useful</p>';
ECHO '</div>';
ECHO '</div>';
ECHO '</a>';
However, the outcome of the php code in browser are as followed:
<div class="header-box">
<a target="_blank" href="http://designinstruct.com/tools-basics/5-easy-steps-optimize-your-images-photoshop/"></a>
<div class="detail">
<a target="_blank" href="http://designinstruct.com/tools-basics/5-easy-steps-optimize-your-images-photoshop/">
<p class="title">5 Easy Steps to Optimize Your Images in Photoshop</p>
</a>
<p class="author"><a target="_blank" href="http://designinstruct.com/tools-basics/5-easy-steps-optimize-your-images-photoshop/">This article is shared by </a><a class="user" href="./member.php?action=profile&id=2">demoname demo</a> on 01 January 1970.</p>
</div>
<div class="good"><p id="number">1</p><p id="icon"><i class="fa fa-thumbs-o-up"></i>Useful</p></div>
<div class="bad"><p id="number">2333</p><p id="icon"><i class="fa fa-thumbs-o-down"></i>Not Useful</p>
</div></div>
I am getting a little bit frustrated trying to fix the problem because I can't figure out what is going wrong? The other part of code written with html link wrapping the div are working fine. Can anyone help me out? Thanks.
So the question was solved by Rick Hitchcock for pointing out my nesting issue.
So the answer is not nesting an tag within another tag.
After seeing the refactored code, I realized you have a link inside another link. The browser doesn't know what to do with this, so it closes them both down as small as they can.
Try using html inside your .php file, and just using tags where you have to use php. For Example:
close the php with a ?>, then open it each time you need it by wrapping your code in
<?php //php code goes here ?>
Here's your code refactored:
<a target="_blank" href="<?php echo $row["link"] ?>">
<div class="header-box">
<div class="detail">
<p class="title"><?php echo $row["title"] ?></p>
<?php $user_data = get_user_data($row["owner_id"]); ?>
<p class="author">This article is shared by <a class="user" href="./member.php?action=profile&id=<?php echo $user_data["id"] ?>"><?php echo $user_data["firstname"] ?> <?php echo $user_data["lastname"] ?></a> on <?php echo date("d F Y", strtotime($row["posted"])) ?></p>
</div>
<div class="good">
<p id="number"><?php echo $row["good"] ?></p>
<p id="icon"><i class="fa fa-thumbs-o-up"></i>Useful</p>
</div>
<div class="bad">
<p id="number"><?php echo $row["bad"] ?></p>
<p id="icon"><i class="fa fa-thumbs-o-down"></i>Not Useful</p>
</div>
</div>
</a>
Why are you using pure PHP for this? Its not necessary?

Why isn't my div showing?

Ignore the horrible code and formating, it's what I have to work with.
<div class="stories-pictures"><div class="inside">
<?php for ($j=0; $j<2; $j++) foreach ($stories as $post) { /* can be empty field as well*/
setup_postdata($post);
if ($post->ID==$mainID && $j==0) {
$link = get_permalink($productID);
$title = "Back to <br/>".get_the_title($productID);
$img = "<img class='backbg' width='316' height='234' src=".get_template_directory_uri()."/images/bg.png";
} else if ($post->ID!=$mainID && $j==1) {
$link = get_the_permalink()."?e=$productID";
$title = get_the_title();
$img = get_the_post_thumbnail(null,'story-thumb');
} else continue;
?>
<a href="<?php echo $link; ?>" class="storiespicture">
<span>
<span><em> <span class="title"><?php echo $title; ?></span></em></span>
</span>
<?php echo $img; ?>
<div class="storieoverlay">
</div> <!-- .storieoverlay -->
</a> <?php } ?>
</div></div>
Here's what's outputted:
<a href="http://hidden/" class="storiespicture">
<span>
<span> <em> <span class="title" style="background-color: rgba(144, 137, 213, 0.901961);">hidden</span></em> </span>
</span>
<img width="316" height="234" src="http://hidden/hidden.jpg" class="attachment-story-thumb wp-post-image" alt="hidden"> </a>
I'm trying to get the .storieoverlay class to be under the img.
I removed some possibly sensitive content, hence where hidden is shown.
It's because you don't close your image tag:
$img = "<img class='backbg' width='316' height='234' src=".get_template_directory_uri()."/images/bg.png";
Should be
$img = "<img class='backbg' width='316' height='234' src='".get_template_directory_uri()."/images/bg.png'>";
I've fixed the issue now.
It was a plugin outputting the mark up on this certain page, everything said here has been useful though, so thanks.

In PHP fetch content and truncate the string or variable, till 3rd breakline then display

//In PHP fetch content and truncate the string or variable, till 3rd breakline then display
//when i use this method the entire div deallocated and the its not displaying properly...hope the fetch content contain some image tags too // ...
<div class="mid-blks-cont">
<!-- Block1 -->
<div class="mid-block-1 boxgrid caption">
<?php
foreach ($querypost as $row) {
$content = $row->post_content;
$pcontent_overview = (strlen($content) > 300) ? substr($content,0,300).'... Read More' : $content;
if($img == "No Image Uploaded" ) {
?>
<img alt="" src="<?php echo base_url(); ?>assets/img/samples/sample1.jpg"style="width: 391px; height:231px"/>
<?php } else { ?>
<img alt="" src="<?php echo base_url(); ?>uploads/<?php echo $row->post_media ;?>" style="width: 391px; height:231px" />
<?php }?>
<h4 class="cat-label cat-label2"><?php echo $row->category;?></h4>
<div class="cover boxcaption">
<h3><?php echo $row->post_title;?><span class="topic-icn"><?php echo $row->comment_count;?></span></h3>
<p> <?php echo $pcontent_overview;?>....</p>
MORE <i class="fa fa-angle-double-right"></i>
</div>
<?php } ?>
</div>
</div>

Grouping database results within while loop

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.

Categories