PHP string concatenation problem? - php

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>

Related

Outputting dynamic PHP code to insert into a dynamically created PHP page

Hey guys got a question on outputting a dynamic PHP block for a dynamically created PHP page. In my code I am looking for a string in an HTML page thats been uploaded. Once found I am replacing the string with a block of PHP code, the HTML page will be saved as a PHP page to be used on the project. So as I am looping through the HTML I am replacing the string with this ($i is replaced with the number in the loop so I can use them in my array.)
$phpCodeNoLink = '<span id="Title'.$i.'"><?php echo $sl_result['.$i.'][2]; ?></span>
<a href="editor.php?<?php echo "vfSID=" . $sl_result['.$i.'][0] . "&vfSection=2&vfSLink=" . $sl_result['.$i.'][4] . "&vfOrderID=" . $sl_result['.$i.'][5] . "&vfID=" . $vfID; ?>" target="_parent">
<img src="images/btn_edit.gif" border="0" id="SL_editButton'.$i.'" class="editButton" />
</a>';
The problem is it is not outputting what I need, example of what it should look like
<span id="Title1"><?php echo $sl_result[1][2]; ?></span>
<a href="editor.php?<?php echo "vfSID=" . $sl_result[1][0] . "&vfSection=2&vfSLink=" . $sl_result[1][4] . "&vfOrderID=" . $sl_result[1][5] . "&vfID=" . $vfID; ?>" target="_parent">
<img src="images/btn_edit.gif" border="0" id="SL_editButton1" class="editButton" />
</a>
This is what I get in the PHP page once it's generated
<span id="Title0"><?php echo $sl_result[0][2]; ?></span>
<a href="editor.php?<?php%20echo%20%20" vfsid=" . $sl_result[0][0] . " .>" target="_parent">
<img src="images/btn_edit.gif" border="0" class="editButton"></a>
The PHP tags are being replaced and I am missing a whole block of code. Am I missing something any help would be much appreciated.
Figured it out, the PHP code was being parsed and removed by my inline CSS converter moving it above all the other parsing resolved it issue...

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; ?>

simple Echo Error

i try to make a while{ part in php, to read out a mysql db. Works perfectly, only with the output i have problems:
echo "<div id=\"content\"><ul class=\"pageitem\"><li class=\"store\"><span class=\"image\" style=\"background-image: url('<?php echo \". $zeile['image'] . \"; ?>')\"></span><span class=\"name\"><?php echo \". $zeile['title'] . \"; ?></span><span class=\"arrow\"></span></li></ul>";
Error is:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\xampplite\htdocs\harti\products.php on line 40
Sry i'm really new with php, i think this is a simple mistake but cannot find it.
thx for help
Don't use <?php again...
echo "<div id=\"content\"><ul class=\"pageitem\"><li class=\"store\"><span class=\"image\" style=\"background-image: url('". $zeile['image'] . "')\"></span><span class=\"name\">". $zeile['title'] . "</span><span class=\"arrow\"></span></li></ul></div>";
Also, you forgot to close the DIV.
Instead, you could do something like this (outside <?php and ?>):
<div id="content">
<ul class="pageitem">
<li class="store">
<a href="index.html">
<span class="image" style="background-image: url('<?php echo $zeile['image']; ?>')"></span>
<span class="name"><?php echo $zeile['title']; ?></span>
<span class="arrow"></span>
</a>
</li>
</ul>
</div>
Read up on how strings work in PHP:
http://php.net/manual/en/language.types.string.php
If you use double quotes you can do this:
echo "<b>{$myarray[$index]}</b>";
Or you can do this:
echo 'blah';
Note how I used single quotes to avoid having to escape the double quotes. However, with a single quote, I cannot embed the variable within the quote.
Try this
echo "<div id='content'><ul class='pageitem'><li class='store'><a href='index.html'><span class='image' style='background-image: url(" . $zeile['image'] . ")'></span><span class='name'>" . $zeile['title'] . "</span><span class='arrow'></span></a></li></ul></div>";
Do not use
try this:
echo "<div id=\'content\'><ul class=\'pageitem\'><li class=\'store\'><a href=\'index.html\'><span class=\'image\' style=\'background-image: url(".$zeile['image'].")></span><span class=\'name\'>".$zeile['title']."</span><span class=arrow></span></a></li></ul></div>";
Check Single quotes also.
And even I agree with "Parkyprg", use html content outside php.
you may replace each " with "+"\""+".
It works in all scripting languages.

Is there a better way to write this php code?

return'
<li>
<img class="avatar" src="images/' . $picture . '" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>' . $username . '</strong> '. autolink($tweet).'
<div class="date">'.relativeTime($dt).'</div><div class="date">'. $reply_info . '</div> <a class ="reply" href="home.php?replyto=#'. $username .'&status_id='. $id .'&reply_name=' .$username.'"> reply </a>
</div>
<div class="clear"></div>
</li>';
I was wondering if there is a cleaner way to write this code, and taking in mind processing time, if that really means anything.
p.s. this code is part of a function, this is the return statement!
Yes. Use double quotes for the PHP string (and single quotes for the HTML attributes), then you can just use PHP variables in the string, like so:
"<a href='nano.com/$username'>";
Is processing time really an issue? I doubt it, but profile to be sure.
Edit: If anyone is unsure about using single quotes in HTML attributes, have a look at this question. It's pretty unanimously agreed that single quotes are fine. If anyone can give a decent counter-argument I'd be happy to hear it.
You could use HEREDOC syntax :
$auto = autolink($tweet);
$rel = relativeTime($dt);
return <<<ENDOFRETURN
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div><div class="date">$reply_info</div> <a class ="reply" href="home.php?replyto=#$username&status_id=$id&reply_name=$username"> reply </a>
</div>
<div class="clear"></div>
</li>
ENDOFRETURN;
Cleaner template and php code -> use MVC
Yes, there is one, and you don't need MVC (only a template):
<li>
<a href="nano.com/<?=$username ?>">
<img class="avatar" src="images/<?=$picture ?>" width="48" height="48" alt="avatar" />
</a>
<div class="tweetTxt">
<strong><?=$username ?></strong>
<? echo autolink($tweet) ?>
<div class="date"><?=relativeTime($dt) ?></div>
<div class="date"><?=$reply_info ?></div>
<a class="reply" href="home.php?replyto=#<?=$username?>&status_id=<?=$id?>&reply_name=<?=$username?>">
reply
</a>
</div>
<div class="clear"></div>
</li>
Must read: http://wiki.yet-another-project.com/php/the_one_single_step_for_a_cleaner_code . It describes how you have to use the code above.
I would cut in several pieces and use sprintf() to tie it all together.
You can use a template engine i.e. smarty, twig, ...

Categories