tags:

views:

142

answers:

7

for example i want to generate html code, using some data from database. here is two ways of printing data


<? echo '<li><img src="'.$row['image'].'" /></li>';?>
or
<? echo "<li><img src='$row[image]' /></li>";?>

both of them are working. and if so, why people use the first method, if without spliting the row by . it works fine too.


thanks

+1  A: 
echo sprintf('<li><img src="%s" /></li>', $row['image']);

Much easier to read and less prone to errors if it get's changed/extended later.

Techpriester
I would even go so far as to suggest using some sort of template system.
Bryan Ross
I'd make this echo sprintf('<li><img src="%s" /></li>', htmlentities($row['image'], ENT_QUOTES)); (well, a URI shouldn't contain "bd" HTML code, but better to be safe)
johannes
@Bryan: Using View-Scripts that just contain output statements like this is already a simple templating system. Zend Framework for example does it this way and it's very nice to use.
Techpriester
But Zend does it not sprintf way
Col. Shrapnel
@Shrapnel: How you actually do your output is not specified in Zend Framework. You can use whatever method you like, that's why it's so nice :)
Techpriester
You have just say "Zend Framework for example does it this way" and now "output is not specified in Zend Framework". Choose one. Anyway, you just gone far away from the topic. Better you just say thanks to the useful Techpriester' comment.
Col. Shrapnel
With "Zend Framework for example does it this way" I was referring to the use of View scripts that contain nothing but output code as a simple way of providing a templating system.
Techpriester
and it was a useless comment because no developer being in right mind would use sprintf for the template.
Col. Shrapnel
+1  A: 

Another method:

<li><img src="<?php echo($row['image']); ?>" /></li>
Bryan Ross
@Bryan Ross yes, you can also write src="<?=$row['image']?>"...i want to know what is the best method
Syom
@Syom that is 100% subjective, as there is negligible performance difference between the variations. All HTML literals in PHP pretty much get turned into echo statements anyways, so it's really just a matter of what looks nicest to you and is easiest to work with.
Bryan Ross
Syom, this won't work on all installations - short tags can be turned off so a portable app can't rely on it.
johannes
@johannes yes, and on some installations can be turned off mysql, cron, mod_rewrite, apache module. We should not use it all of course. Abacus is the best choice for the computing.
Col. Shrapnel
A: 

In the second method:

<? echo "<li><img src='$row[image]' /></li>";?>

you cannot use functions, you can only use variables. It does not matter which method you use if you are printing variables.

+1  A: 
<? echo '<li><img src="'.$row['image'].'" /></li>';?>

A reasonable strategy is to output all static content in plain PHP templating. That way you don't have to worry about PHP string literal escaping in the static content:

<li><img src="<? echo $row['image']; ?>"/></li>

However, (a) you need to use htmlspecialchars() on all raw-text strings output into HTML, or you've got potential cross-site-scripting issues. Also, <? short tags should generally be avoided as they may not be enabled on all servers.

To cut down on the amount of typing “htmlspecialchars” in templates, define a shortcut function:

<?php
    function h($s) {
        echo htmlspecialchars($s, ENT_QUOTES);
    }
?>

<li><img src="<?php h($row['image']); ?>"/></li>
bobince
+1  A: 

The best way would be to use only one method.

BRUL
A: 

If you are using ' in ur html tags for specifying attribute values then use " in PHP and if you are using " in html then use '. Either way you won't need to escape the quote in html by \

Prab
A: 

I'd even use <?php echo '<li><img src="' . $row['image'] . '" /></li>'; ?>

There's a speed difference, but that would be barely measurable and usually not at all noticable. Every string in double quotes is parsed first. That's why it's better to not use double quotes for strings at all. If you use extremely many strings with vars in it, it could become a measurable difference - but doing that would be quite bad design in the first place.

Btw.: The same is true for often switching the parser on and off with <?php and ?>.

The main reason for doing the above is good coding practice.

Others may need to understand your script too. And maybe yourself too some years later. Vars in strings can be easier overlooked than vars included like this. Even more so on IDEs with syntax highlighting.

I've even seen people put a newline before every var inserted in this way. But IMHO that's a little too much. ;)


More or less offtopic: No I didn't read all the fighting going on in the other answers, but I know the old "no it's not slower" vs. 'Yes it is' kindergarden by heart. ;)

For christs sake, you're coders, damnit. Just test it:

<?php
$startt = microtime(true);

for ($i = 0; $i <= 10000000; $i++) {
    $test = 'This is test number ' . $i;
//  $test = "This is test number " . $i;
//  $test = "This is test number $i";
}

$endt = microtime(true);
echo 'Used time: ' . ($endt - $startt);
?>

For me the first one gave 5.1321198940277, the second one 5.2075009346008 and the third one 6.4821639060974 (more than 1.2 secs difference). Q.E.D. so far.

The interesting thing would be to try that on different systems. Maybe I'll make my own question for this.

b_i_d
could you please explain "Every string in double quotes is parsed first" statement? I don't understand both it's meaning and speed difference reason.
Col. Shrapnel
that's totally wrong way of running performance tests. Speed is not among the reasons to choose between printing methods. Any issue you can not measure with real world tests should not to be taken into account. we are coders, yes. but "let's run some useless crap for zillion times" is not a test at all. Why not to use at least `ab` benchmark to query some script doing something sensible?
Col. Shrapnel
Did I step onto your sacret ground, sensei Shrapnel-san? ;)I did talk about speed in my answer. And when you're trying to measure speed it's considered a good practice to measure speed. If that takes a burden of your heart: I ran multiple tests and gave the most average results.Of course asking for CPU cycles, memory, caching, I/O, etc. would be interesting too. But since I didn't talk about it, why would I measure it? Actually I'm a little lazy to set up a whole benchmark suite for that one answer. But feel free to do so yourself, if you feel the need to defend your holy book.
b_i_d
> ..."Every string in double quotes is parsed first"... I don't understand both it's meaning and speed difference reason.For every character supported to be parsed inside strings the parser first checks if there is an expression (like a var or an array key) coming. That's not too expensive, but work that has to be done.With single quotes the parser doesn't need to to that, but can just stream the string, until it hit's the next single quote.Some years ago that used to be quite a difference. As you can see the parser has quite improved in the meantime and it's barely noticeable now.
b_i_d
Well my sacred ground is nothing more than fighting against ignorance and superstitions. And my holy book is called "profiling". And it seems too few people here have heard it's name. You didn't even get what I am saying. I am not talking of memory and CPU. but merely of practical significance of your way of testing. Actually I have done profiling tests for the thousands times. And it never showed any significance for whatever syntax issue. But only for the data manipulation.
Col. Shrapnel
`With single quotes the parser doesn't need to do that, but can just stream the string,` (you can use ``backticks`` to quote too) how come? It's still looking for the \ and '. Yes, for the double quotes the table is bigger but that's just a few additional CASE statements! It is really nothing.
Col. Shrapnel
`As you can see the parser has quite improved in the meantime and it's barely noticeable now.` Look. it is not "barely noticeable" it cannot be noticeably at all. string parsing take 0,0001% of the overall script execution. Improve it even by 10 - it still won't be noticeable at all. That's what I am talking about.
Col. Shrapnel
It's great that you make a living doing that.I don't really care for that, because I find it much easier to just understand in the first place what a given system does under the hood. Analyzing, measuring and fiddling afterwards just isn't my cup of tea.And also after many years of repairing other coders messy and insecure codebase I got tired of it and make a living working self-employed on my own projects now.But nice that you have found something you like.
b_i_d
> string parsing take 0,0001% of the overall script execution.You do realize that the rest of the script stays the same for all three tests? How would the fact that the loop takes eats up most cycles mess up the results? As I said earlier: I did use the best average.And as I also said earlier: That has improved in the last years. Of course I don't know how long you worked with PHP, but there is or was (you can pick one yourself) a reason for the " vs ' war. And that's why old coders still propagate it.
b_i_d
ESPECIALLY when you work in software profiling, you should notice even the smallest places where you can squeeze out a few extra cycles, if it doesn't require extra work.Because on the projects I used to work on, (the last bigger one with millions of lines of code, hundreds of files, thousands of users and an incredible amount of data flowing through it every second) even the smallest things can add up quite a bit.
b_i_d
oh I am impressed with your last project. But of course you have lost a flash drive with the actual profiling results taken from this project. What a pity.
Col. Shrapnel
I see. All arguments are used up, the trolling begins. So it's time for me to call it a day on this discussion. Was a nice one, as long as the niveau lasted. Some last words: I didn't tell you about that project to impress. Boasting isn't my thing. I did tell you about it to prove the point that even microscopic differences can grow quite large. When I took the project over, two servers were dying every 2-3 hours. After two years only one server was needed and even had enough room left to handle the website and customer support on the side. So something about my view seems to be right.
b_i_d