I am studying PHP from a book. The author uses echo to output HTML. At first I thought that this was how it supposed to be done, but then I picked up a more "advanced" book. The author of the second book inserted PHP code between HTML rather then echo the whole thing. How is it done in large web development companies that work on large projects? Can you use either, or is one more accepted than the other?
Take this code for example:
<?php
//pagination
if ($pages > 1) {
//determine the current page
$current_page = ($start / $display) + 1;
//print out Previous Page button
if ($current_page != 1) {
?>
<div class="pages"><strong><a href="view_users.php?s=<?php echo ($start - $display); ?>&p=<?php echo $pages; ?>"> < </a></strong></div>
<?php
}
//print the page numbers
for ($i = 1; $i <= $pages; $i++) {
if ($i == $current_page) {
?>
<div class="pages active"><span> <?php echo $i; ?> </span></div>
<?php
}
else {
?>
<div class="pages"><strong><a href="view_users.php?s=<?php echo ($display * ($i - 1)); ?>&p=<?php echo $pages; ?>"> <?php echo $i; ?> </a></strong></div>
<?php
}//end of $i = $current_page conditional
}//end of FOR loop
if ($current_page < $pages) {
?>
<div class="pages"><strong><a href="view_users.php?s=<?php echo ($start + $display); ?>&p=<?php echo $pages; ?>"> > </a></strong></div>
<?php
}
}//end of pagination
include('includes/footer.php');
?>
Is that the correct way of doing it, or should I use something like this:
echo '<a href="view_users.php?s=' . ($display * ($i - 1)) .
'&p=' . $pages . '&sort=' . $sort . '">' . $i . '</a> ';
The reason why I'm asking is because I find it difficult to properly align the HTML when using the second technique, and I don't want to develop any bad habits early on.
The first method makes your code more readable. The second method is useful when you need to print some little amount of html code. Also you can use short open tags to insert your php code between html tags. For example if you need to print language parameter of URL you can do like this:
<a href="index.php?lang=<?=$lang?>" >A Link</a>
This is equal to this:
<a href="index.php?lang=<?php echo $lang; ?>" >A Link</a>
I'd recommend using a good framework in general, and a templating engine for outputting pages. This way, your data models, your application logic, and your HTML are all kept separate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With