is there any significant difference in these 3 different applications of php - php

I am trying to improve on my programming theory and in a previous question it was pointed out to me that I should not use multi-line ehcos in my programming as show in the first example. I use this because once it is complied it automatically minimizes the out put html. Which of the there examples below is the best practice for making use of php and why?
1)
echo '<div class="row cf">';
echo '<div class="col_8 cf alpha">'.$page_title.'</div>';
echo '<div class="col_4 cf omega right">';
echo '<a href="'.$table_url.'-action.php?action=add" class="button blue">';
echo '<i class="icon-plus-sign"> </i> Add a Site</a>';
echo '</div>';
echo '</div><hr>';
2)
echo '
<div class="row cf">
<div class="col_8 cf alpha">'.$page_title.'</div>
<div class="col_4 cf omega right">
<a href="'.$table_url.'-action.php?action=add" class="button blue">
<i class="icon-plus-sign"> </i> Add a Site</a>
</div>
</div>
<hr>
';
3)
<div class="row cf">
<div class="col_8 cf alpha"><?php echo $page_title; ?></div>
<div class="col_4 cf omega right">
<a href="<?php echo $table_url; ?>-action.php?action=add" class="button blue">
<i class="icon-plus-sign"> </i> Add a Site</a>
</div>
</div>
<hr>
Thanks.... Pete

There is significant difference. The first one is especially hard to maintain. The second is a bit better, but still inconvenient.
The third one allows you to write plain HTML without the need of escaping anything. You only briefly open PHP tags to insert variables. This HTML is also property syntax-highlighted if you got a smart editor like Netbeans or even Notepad++.
So I would choose the third one, except maybe when I insert a very tiny piece of HTML.
If I may suggest a small improvement:
<?php echo $x; ?>
can also be written as
<?= $x ?>
In case of performance, I think there won't be much difference. I would guess that the third one is faster, since it needs to parse and execute smaller pieces of PHP. In the other ones the strings need to be parsed as well to check for special characters.
That said, I doubt if you would be able to measure any difference at all, and it shouldn't be your concern. Choose the one you like best. For optimization, you'd better find real bottle necks, which are ususally found in the area of executing too many, too complex, or poorly optimized database queries.

I prefer solution 3 for two reasons:
My IDE (notepad++) will actually syntax highlight the HTML and the PHP and not just colour it the "string colour". I also do not have to escape ''s in the HTML by changing it to \' every time I use it.

Related

When my variable has an apostophe in it, it cannot be used for onshow

I'm using a conditional in templating engine tinybutstrong to show a <div> when a variable is not blank.
<div class="notice">[onshow;block=div;when [var.notice;noerr]!=''][var.notice;noerr]</div>
It works well except for when the $notice variable has an apostrophe ' in it. Otherwise the onshow conditonal doesn't run.
How do I fix this?
The values may have quotes, you have to use delimiters and escaping :
<div class="notice">
[onshow;block=div;when '[var.notice;strconv=esc;noerr]'!='']
[var.notice;noerr]
</div>
The manual has been updated in order to have this clearer.
But is you case, using a magnet seems smarter:
<div class="notice">
[onshow.notice;noerr;magnet=div]
</div>

How to style the output of an echo to display a grid?

My team and I have made a database in php my admin for a restaurant, and I'm currently working on the customer dashboard. Im using for each loops to display complete orders in one of the dashboard tabs, and have the code working, but right now it just outputs regular black text. I was wondering how to style it to output the rows as a grid, similar to bootstrap grids.
I've tried to just add containers with rows and columns to the foreach echo itself, but its just not working as I thought it would.
<div id="CurrentOrders" class="tabcontent" style="margin-left: 24px">
<!-- This information will be pulled from the Orders table in the DB -->
<h3>Current Orders</h3>
<p>
<div class="container">
<?php
foreach ($orderno as $order) {
$n = $order['OrderNo'];
$menunamequery = "SELECT * FROM OrderItem WHERE OrderNo = '{$n}'";
$currentorders = getRows($menunamequery);
foreach ($currentorders as $currentorder) {
echo "Order Number -"." ".$currentorder['OrderNo']." , "."Order -"." ".$currentorder['MenuName']." , "."Quantity -"." ".$currentorder['Quantity']."<br>";
}
}
?> </div>
</p>
</div>
The expected result is for these rows im outputting to have some sort of grid layout, the actual result is just plaintext currently.
Sorry if this is a bad question, my team and I just learned php this semester and are hoping to continue getting better at it. Any help would be appreciated.
You can simply output HTML from PHP:
echo '<span style="color: red">'.$currentorder['MenuName'].'</span>';
However, it is advised that you sanitize your output, so nobody can "create HTML" by putting tags in the database;
echo '<span style="color: red">'.htmlspecialchars($currentorder['MenuName']).'</span>';
This does exactly what it says; makes HTML entities from special characters. For example, > will be printed as >, which the browser will safely render as >, instead of trying to interpret it as an HTML element closing bracket.
Alternatively, you can simply write HTML directly if you wish, by closing and opening the PHP tags:
// PHP Code
?>
<span class="some-class"><?=htmlspecialchars($currentorder['MenuName'])?></span>
<?php
// More PHP Code
You may also want to look into templating engines to make it easier for you, although it depends on the project if it's worth it for you to look into that, since there is a little bit of a learning curve to it.

How to easily commenting PHP+HTML code

Especially for easy and small projects, I leave pure HTML in my PHP source code and I simply add the relevant PHP when needed, and so many times I have something like this:
<div class="header-info">
<p><?php echo $w["emailText"][$lang];?></p>
</div>
Now, apart from it being good or bad practice, how can I easily comment out the whole 3 lines?
If I enclose them in HTML comments like these (sorry for the space but otherwise they are not printed):
< !--
... my code ...
-->
then PHP is still executed. If I enclose them in something like
<?php
if (0) {
?>
... my code ...
<?php
}
?>
then the nested "?>" will close my PHP if(0).
Again, I am fully aware that I should better use a Model-View-Controller approach and not mix different "worlds", but as said, for small projects it does not make sense and I am just asking if there is another solution to the 2 that I proposed :)
Thank you
If you do not needed, why not remove it completely? If you want to prevent div tag from outputing to browser, then you can comment all of them, like following.
<?php /*
<div class="header-info">
<p><?php echo $w["emailText"][$lang];?></p>
</div>
*/ ?>

Store Javascript function in PHP

I can't for the life of me figure out how to store this javascript function in a php variable. Basically I want to store this function as a standard string in a php variable, and then it get's printed out on a page. I know that I have to escape javascript to have it work with PHP, but the reason I'm stuck on this is because this particular Javascript and HTML combination seems to make use of both " and ' so I can't figure out how to escape it. Maybe you guys could help me out?
Here's the code I want to store in the php variable:
<a href='javascript:PopupContact_OpenForm("PopupContact_BoxContainer","PopupContact_BoxContainerBody","PopupContact_BoxContainerFooter");'><img src='/popup-contact-form.jpg' /></a>
<div style="display: none;" id="PopupContact_BoxContainer">
<div id="PopupContact_BoxContainerHeader">
<div id="PopupContact_BoxTitle">Contact Us</div>
<div id="PopupContact_BoxClose">Close</div>
</div>
<div id="PopupContact_BoxContainerBody">
<form action="#" name="PopupContact_Form" id="PopupContact_Form">
<div id="PopupContact_BoxAlert"> <span id="PopupContact_alertmessage"></span> </div>
<div id="PopupContact_BoxLabel_Page"> Your Name </div>
<div id="PopupContact_BoxLabel_Page"><input name="PopupContact_name" class="PopupContact_TextBox" type="text" id="PopupContact_name" maxlength="120"></div>
<div id="PopupContact_BoxLabel_Page"> Your Email </div>
<div id="PopupContact_BoxLabel_Page"><input name="PopupContact_email" class="PopupContact_TextBox" type="text" id="PopupContact_email" maxlength="120"></div>
<div id="PopupContact_BoxLabel_Page"> Enter Your Message </div>
<div id="PopupContact_BoxLabel_Page"><textarea name="PopupContact_message" class="PopupContact_TextArea" rows="3" id="PopupContact_message"></textarea></div>
<div id="PopupContact_BoxLabel_Page"><input type="button" name="button" class="PopupContact_Button" value="Submit" onClick="javascript:PopupContact_Submit(this.parentNode,'/popup-contact-form/');"></div>
</form>
</div>
</div>
<div style="display: none;" id="PopupContact_BoxContainerFooter"></div>
Hopefully you can see what I mean, I want to store it in my $button variable
Thanks!
You could put the whole thing in single quotes and then escape every single quote within it like \', but a much nicer approach would be to use PHP's nowdoc syntax:
$str = <<<'STR_HTML'
// All your HTML goes here
STR_HTML;
If you're PHP version is earlier than 5.3 you can't use nowdoc, so you should use heredoc instead. The difference is like the difference between double quotes (heredoc) and single quotes (nowdoc).
See the PHP manual page on strings for more information.
The best thing you can do, is to move your JavaScript functions to separate files. Mixing them into your PHP will create a lot of clutter.
In your PHP:
<html>
<head>
<script src="path/to/my/script.js"></script>
</head>
<body>
....
</html>
In the script file:
function PopupContact_OpenForm( ... ) {
...
}
This will make it much more easy to organize your source code and add more functions without mixing PHP and JavaScript.
(If you still want to keep everything in the PHP file, use HEREDOC as the others suggest.)
heredoc syntax to the rescue!
It's really not good to have all of that in a variable mixing code and html.
To answer your question though, use a heredoc:
$bar = <<<LABEL
Nothing in here...
LABEL;

Would writing HTML with PHP's echo vs writing plain HTML cause any differences in performance?

Which is better in terms of CPU optimization for a web server? Writing plain HTML and inserting PHP code here and there?
<script type="text/javascript">$(document).ready(function(){$('#search').focus();});</script>
<div id="default">
<div class="left">
<?include(DIR_DIV.'facebook.php')?>
</div>
<div class="right">
<?include(DIR_ADS.'google.300x250.php')?>
</div>
<div class="sep"></div>
</div>
Or writing the all the HTML with echo in PHP?
echo '<script type="text/javascript">$(document).ready(function(){$(\'#search\').focus();});</script>';
echo '<div id="default">';
echo '<div class="left">';
include(DIR_ADS.'google.300x250.php');
echo '</div>';
echo '<div class="right">';
include(DIR_DIV.'facebook.php');
echo '</div>';
echo '<div class="sep"></div>';
echo '</div>'
Does the difference even matter or is it insignificant?
finally, does the difference even matter or is it insignificant?
It doesn't matter performance wise, it's completely insignificant.
It does matter readability wise though - I find the first block far more legible than the second one. Wrapping HTML into PHP code like that doesn't make sense - it becomes harder to debug, for one thing.
First block is what might be called php template, second pure PHP.
It really depends on what you will be writing more. If HTML - use first, if PHP still use first, just separate it to different file and use as template :)
If you were writing an entire page (and a complex one) with echo you may add a little bit of overhead, since all those lines would need to be executed server side.
I try to stay away from that for the readability issue mentioned in the other answer, though there may be cases (like having to branch based on some values) where you may need to use this approach.
There is really no difference between the two when it comes to how the server will see it. It all comes down to how easy it would be to update it. you can have issues with single and double quotes because you would need to make sure to escape the same type of quotes that you are using to contain the html. like
echo " <span class=\"first\">".$first."</span>";
This can be a pain some times in long pages.

Categories