PHP tag nested in If statement? - php

The code problem:
<?php
if(strtolower($item["category"]) == "books" ) {
?>
<tr>
<th>Category</th>
<td><?php echo $item["category"] ?></td>
</tr>
<?php } ?>
Why I have to write it like that? Instead of:
<?php
if() {
Do some things!
}
?>

You can write PHP in HTML but you cant write HTML IN PHP(without using echo).
AFTER THIS
<?php
if(strtolower($item["category"]) == "books" ) {
?>
You close the php tag to add html.
Then you open the php tag to put the closing braces for if and then close it back so that you can add html

This is just basic stuff, but short explanation is that when server is processing your *.php file and sending it to the browser it starts parsing your file when he sees <?php tag and stops parsing when he runs into ?> tag or the end of the file. So, anything in between those two will be seen by the server as a PHP code and the rest will be sent directly to browser.
Your code above can be written in several different ways to do the same thing, all depends on what you want to do. This is also valid in PHP and sometimes it's much more readable
<?php if (strtolower($item["category"]) == "books"): ?>
<tr>
<th>Category</th>
<td><?php echo $item["category"] ?></td>
</tr>
<?php endif; ?>

Related

PHP inside MVC's view

I want to separate my presentation layer from the logic layer but I'm unsure what I should do when I have to loop or check stuff within the presentation layer?
Variables and other somewhat static content is easy, I can either do
<div class='description'><?php echo $product['description']; ?></div>
or
<div class='description'>{{product_description}}</div>
But how about looping stuff?
Let's say I'm creating a list of users within a table. Is there any other way except putting up a foreach within the view and printing HTML inside the foreach?
<table>
if (!empty($users)) {
foreach ($users as $key => $value) {
echo "<tr data-user-id='$value[id]'>";
echo "<td>$value[id]</td>";
echo "<td>$value[first_name]</td>";
echo "<td>$value[last_name]</td>";
echo "<td><a href='?id=$value[id]&edit=1' class='edit'>Edit</a></td>";
echo "</tr>";
}
}
</table>
This would work perfectly fine but I can't get over the fact that it's not looking so "viewish" anymore. Is it possible to get the view cleaner? What about when I have to add conditions? It gets more and more messy.
Sounds like the main problem your having has to do more with making the view presentation readable. An easy way to accomplish this using PHP templates is to use the alternative syntax for control flow structures. Doing this can make a template look much more readable, similar to twig for instance.
Using your example:
<table>
<?php if (!empty($users)): ?>
<?php foreach ($users as $key => $value): ?>
<tr data-user-id="<?php echo $value[id]; ?>">
<td><?php echo $value[id]; ?></td>
<td><?php echo $value[first_name]; ?></td>
<td><?php echo $value[last_name]; ?></td>
<td>Edit</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</table>
Notice that I've removed the open curly braquet { and replaced it with a :. This is then closed on line 10 with a endif;. Same idea is repeated with foreach. This is the alternate syntax for control structures. Normally in business logic You would us the other form, but this can really help when you need to write readble template code for view presentation layers.

Browser crashes because of PHP

Idea:
I want to do a print layout, my solution is by absolute div's. to fill it, i use php.
On every page is a table. On one page is enough space for 10 rows.
So i do the following code to prevent more than 10 rows on a page, the rest gets ignored (im solving this later by a message).
here is the code:
<table>
<?php $i=1;
while($info5=mysqli_fetch_array($data5)): ?>
<?php while($i <'10'):?>
<tr>
<td width="50px"><?php echo $i; ?></td>
<td> foo </td>
<td> bar </td>
</tr>
<?php endwhile; ?>
<?php $i++; endwhile; ?>
Unfortunately this code causes firefox, chrome and IE to break. The site starts loading, and then freezes, ending up in a "send crash report".
Why?
$i++;
Should be inside the inner while, otherwise $i always remains 1 and that generates an endless loop and that is what causes your page to crash.
Like this
<?php $i++;?>
<?php endwhile; ?>
<?php endwhile; ?>

A lot of opening/closing of PHP tags

I've always wondered: does having a large open and close PHP (i.e. a template) hurt?
To clarify:
<html>
<?php echo $test; ?>
<body <?php echo $test2; ?>>
<table>
<?php foreach ($rows as $row): ?>
<tr>
<td><?php echo $row['cell1']; ?></td>
<td><?php echo $row['cell1']; ?></td>
<td><?php echo $row['cell1']; ?></td>
<td><?php echo $row['cell1']; ?></td>
<?php echo $row['added cells']; ?>
</tr>
<?php endforeach; ?>
</table>
<?php echo $someMorePhp; ?>
<div>
<?php /*do some more php stuff */ ?>
</div>
etc etc
etc
Or would it be advisable to i.e.
<html>
<php echo $test.'<body'.$test2; ?>>
<table>
<?php foreach ($rows as $row) {
echo '<tr>
<td>'.$row['cell1'].'</td>
<td>'.$row['cell2'].'</td>
<td>'.$row['cell3'].'</td>
<td>'.$row['cell4'].'</td>
<td>'.$row['cell1'].'</td>
'.$row['added cells'].'
<tr>';
}
</table>
// etc
I know this might seem like a micro optimization and such. To be clear i'm looking for a rule-of-thumb not a specific usecase... Will it hurt entering and exiting the php engine during a single script run...
No, that is no problem, you should always opt for better readability in this case.
Also think about either activating shorttags if possible (but beware, those might have some sideeffects / problems with XML sytnax as stated in the comments)
<? if ($bool) { ?>
<?= $myVarThatIWantToOutput ?>
<? } ?>
Or think about using a template engine like smarty or twig, which restrict you somehow to force splitting of concerns, make some stuff easier (and more readable) and allow caching of compiled templates to make sure you still get the right speed.

How is this PHP while loop code creating new table rows?

You can see that I have a 3 element array. I am using a while loop to then print out all 3 values into a table, one row for each of the three values, but I do not understand how three rows are being printed out when I only have one row hard coded using html code. The PHP while loop does not echo the tr and td tags for each row because those row and detail tags are outside the PHP code. The code works -- it prints out one additional new table row for each value of "mary","donna","shirley", but I do not understand how. I could see it working if the tr and td tags were output by a PHP echo statement inside the while loop, but that is not the case here.
<html>
<body>
<table cellspacing ="2" cellpadding ="2" align ="center" border="8">
<?php
$ar1=["mary","donna","shirley"];
$len=count($ar1);
$ct=0;
?>
<?php while ( $ct<$len) { ?>
<tr>
<td>
<?php echo $ar1[$ct];
$ct++;
?>
</td>
</tr>
<?php } //end while loop?>
</table>
</body>
</html>
I believe the answer lies in the fact that HTML is an interpreted language not a compiled language.
So in this case your php while loop is setting the browser back to the spot just before your first tr tag so it goes through and interprets those tags again, and as it does this it puts them to the page again. Doing your while loop like this is a cheap way to do echos essentially.
I'm not a PHP master by any means, but from my understanding of how HTML is read and how PHP works this is my answer.
Your <tr> tag is inside the while loop. If you want just one row, try this-
<html>
<body>
<table cellspacing ="2" cellpadding ="2" align ="center" border="8">
<?php
$ar1=["mary","donna","shirley"];
$len=count($ar1);
$ct=0;
?>
<tr>
<?php while ( $ct<$len) { ?>
<td>
<?php echo $ar1[$ct];
$ct++;
?>
</td>
<?php } //end while loop?>
</tr>
</table>
</body>
</html>
This piece of code:
<?php while ( $ct<$len) { ?>
<tr>
<td>
<?php echo $ar1[$ct];
$ct++;
?>
</td>
</tr>
<?php } //end while loop?>
is the same as
<?php while ( $ct<$len) {
echo "<tr>
<td>";
echo $ar1[$ct];
$ct++;
echo "</td>
</tr>";
} //end while loop?>
if you analyze code more deeply..u will understand it yourself..you said "The php while loop does not echo the tr and td tags for each row because those row and detail tags are outside the php code"
but it does ..the html code is not the part of php code it coded outside php scope...and whenever your while loop executes it again reads the tr and tg tag and insert row and hence u get three rows printed ...
It's an easy case of PHP basic capabilities.
See http://php.net/manual/en/language.basic-syntax.phpmode.php
Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content.
PHP parser, don't need to know what is inside the While Loop, it just repeat to the output.
In a php file, by escaping the php code (by way of ?> you basicly say to the script, now comes something non php, you provide Html tags which are then interpreted by the browser as html code. But because you're still in the loop (you haven't ended it by adding an closing tag } you repeat the exit from the code, presenting html, and then entering the code again.
Some coders prefer to just exit php code and to show some html code with a few php tags here and there when there's a large amount of html being displayed. It's a lot less typing than continually using echo statements.

PHP do-while with HTML in between

I am trying to write PHP code to loop through an array to create an HTML table. I have been trying to do something like:
<div id="results">
<table class="sortable">
<?php $results = $statement->fetchAll(PDO::FETCH_ASSOC); ?>
<?php do: ?>
<tr>
<?php for ($i = 0; $i < count($columns); $i++): ?>
<td><?php echo $row[$i] ?></td>
<?php endfor; ?>
</tr>
<?php while (($row = next($results)) != false); ?>
</table>
</div>
So 2 questions:
Is there an equivalent do-while
syntax as there is a for, if, or foreach syntax in
PHP, where you can split the PHP
code up and have HTML in between?
What is this called when you split
PHP code up with HTML in between?
(if there is a special term for it)
I do not know of a do while syntax that behaves like that, but you can still end your PHP block like this:
<div id="results">
<table class="sortable">
<?php $results = $statement->fetchAll(PDO::FETCH_ASSOC); ?>
<?php do { ?>
<tr>
<?php for ($i = 0; $i < count($columns); $i++): ?>
<td><?php echo $row[$i] ?></td>
<?php endfor; ?>
</tr>
<?php } while (($row = next($results)) != false); ?>
</table>
</div>
You can use curly brackets:
<?php do { ?>
foo
<?php } while ($i--); ?>
No. From http://php.net/manual/en/control-structures.alternative-syntax.php :
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch.
On the other hand, do { ?> ... <?php } while(...) will work just fine.
What you're trying to do can be done with two foreach loops :
<div id="results">
<table class="sortable">
<?php foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row): ?>
<tr>
<?php foreach ($row as $element): ?>
<td><?php echo $element ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
</div>
It solves the problem of having to initialize $row (and handling the empty list special case).
I'm not aware of any specific name for this, but I suspect that if you said "embedded HTML inside my PHP", people would understand.
While I've never used the colon syntax as in your example, everything looks basically right except that on your first time through $row is unassigned.
I would switch it around to look like this:
<div id="results">
<table class="sortable">
<?php $results = $statement->fetchAll(PDO::FETCH_ASSOC);
if ($results) {
while ($row = next($results)) {
?>
<tr>
<?php for ($i = 0; $i < count($columns); $i++): ?>
<td><?php echo $row[$i] ?></td>
<?php endfor; ?>
</tr>
<?php }
} ?>
</table>
</div>
This is excessive use of the embedded php tags.. When there is more PHP than HTML, you're better off using PHP and echoing the HTML.
You can mix php and html in every kind of loop, but your current loop does will not work because $row is not defined the first time it gets there.
It doesn't have a special name :)
You may find using the heredoc syntax a bit cleaner than stepping in and out of PHP / HTML like this, though: http://php.net/manual/en/language.types.string.php
You can use variables inside heredoc blocks so you'll be able to access your database results actually inline without dancing about with braces and new lines.
1) Your best bet is to echo the HTML in strings, all within the <%php ... ?> tag.
What you're doing now is an empty for loop inside of a do-while, which is essentially pointless.
2) I believe that's called "inline" coding, where the code and HTML intermingle, but the practice is frowned upon because you generally want to separate logic (PHP) and content (HTML) when developing for the web.

Categories