Need to loop a block of code using while loop - php

The content is comming from a query and I dont whant to manually generate a long and repetitive block of code, so I thoght it would work nice if I put the first chunk into a while loop but, nothing good comes out of it.
Here is what I got so far...
<?php
$bloq_1 = array(1,2,3,4,5,7,8,9,10);
$blnu_1 = '1';
while( $bloq_1=$numeral_1) {
echo $numeral_1="<article class=\"notxtras\">
<a class=\"notxtras_url_cntn\" href=\"cdn.php?".$tema_s[$blnu_1++]['pltfrm']."=".$tema_s[$blnu_1++]['notid']."\" title=\"".$tema_s[$blnu_1++]['ttl']."\">
<div class=\"notxtras_img_cntn\">
<img src=\"http://cadenanoticias.mx/img/miniatura/".$tema_s[$blnu_1++]['pic1'] ."\" alt=\"".$tema_s[$blnu_1++]['rlcn'] ."\">
</div>
<h1 class=\"notxtras_ttl_cntn\">".$tema_s[$blnu_1++]['ttl']."</h1>
<p class=\"notxtras_brv_cntn\">".$tema_s[$blnu_1++]['brv'] ."</p>
<p class=\"notxtras_dsp_cntn\">Por: ".$tema_s[$blnu_1++]['aut'] ." • ".$tema_s[$blnu_1++]['cdd']." • ".ucfirst(strftime("%A %e de %B del %Y",date(strtotime($tema_s[$blnu_1++]['fch'])))) ."</p>
</a>
</article>";
}
?>
Is it posible?

I have three suggestions/comments:
If the content comes from a query, it would probably be better to use foreach to iterate over the actual query results (which appear to be stored in $tema_s), rather than iterating over a range of numbers. I don't know exactly how $tema_s is populated, but if it's like most other query results I've seen, you're probably missing item 0 if you use [1,2,3,4,5,7,8,9,10]. If you're doing this in order to only show ten results, it would be much better to add a LIMIT clause to your query so you won't be fetching more data than you need.
In cases where you find yourself echoing lots of HTML, it may be better to exit from PHP to produce the HTML, and just echo values from PHP where you need them. This will prevent the annoyance of escaping all those quotes, and the mess it will create when you miss one (not saying you have in this case, but it's quite easy to do.)
None of your variables have been properly escaped for HTML output.
Adjusting the code according to these ideas would be something like this:
<?php
foreach ($tema_s as $item):
$query_string = urlencode($item['pltfrm']. '=' .$item['notid']);
$title = htmlspecialchars($item['ttl']);
$src = urlencode($item['pic1']);
$alt = htmlspecialchars($item['rlcn']);
$date = ucfirst(strftime("%A %e de %B del %Y", date(strtotime($item['fch']))));
?>
<article class="notxtras">
<a class="notxtras_url_cntn" href="cdn.php?<?= $query_string ?>" title="<?= $title ?>">
<div class="notxtras_img_cntn">
<img src="http://cadenanoticias.mx/img/miniatura/"<?= $src ?>" alt="<?= $alt ?>">
</div>
<h1 class="notxtras_ttl_cntn"><?= $title ?></h1>
<p class="notxtras_brv_cntn"><?= htmlspecialchars($item['brv']) ?></p>
<p class="notxtras_dsp_cntn">
Por: "<?= htmlspecialchars($item['aut']) ?>
• <?= htmlspecialchars($item['cdd']) ?>
• <?= $date ?>
</p>
</a>
</article>";
<?php endforeach; ?>
Also, as mentioned in the comments on your question, you should consider looking into a template system, such as twig. It may seem like overkill for what you're doing here, but it takes care of a lot of this kind of stuff for you.

This should work:
<?php
$bloq_1 = array(1, 2, 3, 4, 5, 7, 8, 9, 10);
foreach ($bloq_1 as $blnu_1) {
echo "<article class=\"notxtras\">
<a class=\"notxtras_url_cntn\" href=\"cdn.php?" . $tema_s[$blnu_1]['pltfrm'] . "=" . $tema_s[$blnu_1]['notid'] . "\" title=\"" . $tema_s[$blnu_1]['ttl'] . "\">
<div class=\"notxtras_img_cntn\">
<img src=\"http://cadenanoticias.mx/img/miniatura/" . $tema_s[$blnu_1]['pic1'] . "\" alt=\"" . $tema_s[$blnu_1]['rlcn'] . "\">
</div>
<h1 class=\"notxtras_ttl_cntn\">" . $tema_s[$blnu_1]['ttl'] . "</h1>
<p class=\"notxtras_brv_cntn\">" . $tema_s[$blnu_1]['brv'] . "</p>
<p class=\"notxtras_dsp_cntn\">Por: " . $tema_s[$blnu_1]['aut'] . " • " . $tema_s[$blnu_1]['cdd'] . " • " . ucfirst(strftime("%A %e de %B del %Y", date(strtotime($tema_s[$blnu_1]['fch'])))) . "</p>
</a>
</article>";
}

Related

Advice on cleaner way to write this While statement

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.

PHP+HTML Syntax

I am trying to get a webpage to display four divs that will hold an img and a description. I would like to use a loop because I will have other pages with many of these divs. Here is the code I am using now:
for ($i=0;$i<4;$i++)
{
echo '<div class="item">
<img src="IMGs\\' . $items[$i]["ImgFilename"] . '" />
<h6 class="panel">Description</h6>
</div>';
}
I believe the problem is that I am not escaping the correct way. I have been searching for a while but cannot find the right combination. Files are stored in IMGs\file.jpg where file.jpg is pulled from the array.
Your escaping seems fine to me. However, I think the problem is with the double backslash. Eg, remove the \\ and replace it with / So that line becomes:
<img src="IMGs/' . $items[$i]["ImgFilename"] . '" />
U dont need to escape this.
change this:
<img src="IMGs\\' . $items[$i]["ImgFilename"] . '" />
to <img src="IMGs/' . $items[$i]["ImgFilename"] . '" />
You can lay that code out a little better by breaking in/out of PHP as required, here's a quick example:-
<?php for($index = 0; $index < 4; $index++): ?>
<div class="item">
<img src="IMGs/<?php echo $items[$index]["ImgFilename"]; ?>" />
<h6 class="panel">Description</h6>
</div>
<?php endfor; ?>

Different meaning in the mysql code?

$result=mysql_query("select * from dosyabegeni where veri_id='" . get_custom_field('dwcode') . "'");
Not Working
It says the number and the screen, but the application does not work
veri_id='" . get_custom_field('dwcode') . "'");
veri_id='" . echo get_custom_field('dwcode') . "'");
Working
veri_id='HelloTest'");
veri_id='1234567890'");
veri_id='" . $_GET['test'] . "'");
Main Codes
<?php
include('/home/emre2010/public_html/EntegreOz/DosyaBegeni/config.php');
$result=mysql_query("select * from dosyabegeni where veri_id='" .get_custom_field('dwcode') . "'");
while($row = mysql_fetch_array($result))
{
$sira_id=$row['sira_id'];
$veri_id=$row['veri_id'];
$begeni=$row['begeni'];
?>
<div class="reviewbox">
<div class="summarywrap">
<div class="summarywrapinner">
<div class="summary">
<div class="reviewsection"><div class="rating points">
<a href="#" class="begeni" id="<?php echo $sira_id; ?>">
<span style="color:#fff;" align="center"> <?php echo $begeni; ?> </span>
</a>
<p class="ratingtext">completed!</p></div>
</div><div class="clear"></div>
<div class="clear"></div>
</div>
<div class="ratingsummary"></div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
What's the problem?
Are you meaning to run the review box from within the while loop? If your SQL is only supposed to return one row, you really shouldn't have all that stuff within the while loop. I don't see an end bracket. If you are then you're doing it pretty archaically. You should put the information from the while loop into an array instead and then run a separate loop in your content, but that's not really going to solve the problem. The only issue you could have is either not returning rows because they don't exist, or an error in your SQL.
If your SQL query isn't returning any rows then you need to do two things. One, echo out the sql query. And two, print any possible errors.
echo $sql.'<br />';
print(mysql_error());
You never know, you might have misspelled a column on the table of the db itself.
If that's not working, then print the $row out.
Outside of your while loop do:
print_r($row);

How do I give separate classes to the styling of the month and year in the Wordpress Date function?

I'm in wordpress, trying to format the date output. This is the code I'm using at present:
<div class="date"><?php the_date('M, Y'); ?></div>
It's output looks like this:
MAY, 2010
What I want to do is have the date display like this (The month on top of the year):
MAY
2010
I'm just not familiar enough with PHP to get things working. A simple line break wouldn't quite be sufficient because I want to play with sizing, placement of each separately (month text larger than the year text, both centered, etc.). Separate classes applied to each would be ideal.
mmmm... I did some more searching and, while I still don't know how to get the "the date" function to display multiple lines correctly, using the "the time" function seems to do the same thing without breaking. Here's the code I'm using. Works great.
<div class="month"><?php the_time(M) ?></div><br />
<div class="year"><?php the_time(Y) ?></div>
<div class="date">
<span class='month'><?php the_date('M');?></span>
<span class='year'><?php the_date('Y'); ?></span>
</div>
You can then set the spans to display: block if you want them to each be on their own line:
<style type='text/css'>
.date span { display: block ; }
</style>
Actually, a line break is a good place to begin:
<div class="date"><?php the_date('M'); ?><br /><?php the_date('Y'); ?></div>
And then add additional CSS as needed. For example, if you then add div's, it becomes apparent that the line break can go away, since separate div's will break on their own as long as the display: property on the parent div (#date) is block.
e.g.:
<div class="date"><div style="something-special..."><?php the_date('M'); ?></div><div style="something-else..."><?php the_date('Y'); ?></div></div>
you should be able to just do
<?php the_date('M<b\r>Y')?>
or any other tags making sure you escape the characters listed here
Put this in your themes functions.php and customize with instructions from http://codex.wordpress.org/Formatting_Date_and_Time
// Add date
function post_date() {
$date = explode(",", get_the_time("F,j,Y", "", "", false));
echo '<div class="post-date">';
echo '<div class="container">';
echo '<div class="month">' . $date[0] . '</div>';
echo '<div class="day">' . $date[1] . '</div>';
echo '<div class="year">' . $date[2] . '</div>';
echo '</div>';
echo '</div>';
}
And then use
<?php post_date(); ?>
where you want the date to show up.
<?
$day = get_the_date('j');
$mnth = get_the_date('M');
?>
<div class="cor-date">
<p><?php echo $day; ?><br><?php echo $mnth; ?></p>
</div>

PHP string concatenation problem?

function formatUpdate($tweet,$dt,$picture,$username)
{
if(is_string($dt)) $dt=strtotime($dt);
$tweet=htmlspecialchars(stripslashes($tweet));
$at = "#" . $username;
return'
<li>
<img class="avatar" src="images/' . $picture . '" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>' . $username . '</strong> '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?[^\s\"\']+)/i','$1',$tweet).'
<div class="date">'.relativeTime($dt).'</div> <a class ="reply" href="?replyto=' echo $at; '">reply</a>
</div>
<div class="clear"></div>
</li>';
}
bolt is right. often concat issue has to do with a confusion of mixed in code, literals, and closing quotes/double-quotes. try to use heredoc instead to clean up your code-block.
for example, i would do the following to save my eyes staring at the code and to save my mind from insanity trying to find where the syntax error is (pseudo-coding only):
$at = "#$username";
$rt = relativeTime($dt);
$out = <<<raw
<div class="date">$rt</div>
<a class ="reply" href="?replyto=$at">reply</a>
raw;
just look at how much simpler it looks eh?
to learn about heredoc here's a reading reference.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
To append the value of a variable to a string you need not echo the variable.
You have
href="?replyto=' echo $at; '">reply</a>
Change it to
href="?replyto='. $at .'">reply</a>

Categories