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.
Related
noob problem: i have some issues with a loop in php...here is the code (i used the same methodology for other pages and it works); the code it is supposed to display the names of the products from a order, it works, but it is not showing the very first product , i don't know why :
<?php $i=1; while($row_selectOrderItems = mysqli_fetch_array($result_selectOrderItems)){ ?>
<tr>
<td> <?php echo $i; ?> </td>
<td> <?php echo $row_selectOrderItems['pro_name']; ?> </td>
<td> <?php echo $row_selectOrderItems['pro_price']; ?> </td>
<td> <?php echo $row_selectOrderItems['q']; ?> </td>
<td> <?php echo $row_selectOrderItems['q']*$row_selectOrderItems['pro_price']; ?> </td>
</tr>
<?php $i++; } ?>
and here is the code where i used mysqli_fetch_array before the loop
$query_selectOrderItems = "SELECT *,order_items.quantity AS q FROM orders,order_items,products WHERE order_items.order_id='$order_id' AND order_items.pro_id=products.pro_id AND order_items.order_id=orders.order_id";
$result_selectOrderItems = mysqli_query($con,$query_selectOrderItems);
$row_selectOrderItems=mysqli_fetch_array($result_selectOrderItems);
Does anyone have any idea how should i modify this code? Thank you!
You're reading and ignoring the first record in the results. Consider how your loop works:
while($row_selectOrderItems = mysqli_fetch_array($result_selectOrderItems))
Each iteration calls mysqli_fetch_array, stores the record in $row_selectOrderItems, then uses that to display the record. Then consider what you do before the loop:
$row_selectOrderItems = mysqli_fetch_array($result_selectOrderItems);
You're doing exactly that same thing, but not displaying that first record.
Simply remove that first call to mysqli_fetch_array before the loop.
$row_selectOrderItems=mysqli_fetch_array($result_selectOrderItems);
remove this line, so that, it will not read the 1st result at starting.
Now, when you use it in the while loop, it reads the first line
may be you used mysqli_fetch_array($result_selectOrderItems) before this for loop.
check once
I'm trying to solve this current problem which I could use some help with:
From the database using php, the page must load an X number of sections, every section has some content on top, a table and some content on the bottom, the table can have 0 to any number of rows, depending on what was previously in the database.
Aside from the table the rest of the content doesn't vary in size.
I cannot know beforehand what will be the size of each section because of the table, and there is usually at least 30 sections.
This page must be print friendly, and aside from the page-breaks everything is already working.
I need to find a way to dynamically add page-breaks to fit the sections into the page without cutting them between pages.
The code is about 400 lines so it wouldn't be practical to post it here, but the section structure is something like this:
<section class="row">
<section>
<section class="col-md-2"></section>
<section class="col-md-8 printcenter">
<p class="docenteheader" >
<span class="tabspaceright">NAME: <strong>name</strong></span>
<span class="tabspaceleft">ID: <strong>number</strong></span>
</p>
<table>
<tr>
<th><strong>1:</strong></th>
<th><strong>2:</strong></th>
<th><strong>3:</strong></th>
<th><strong>4:</strong></th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
<p><strong>Something1:</strong> Something</p>
<p>
<span><strong>Something2: number</strong></span>
<span ><strong>Something3: number</strong></span>
</p>
<section class="rel_endline"></section>
</section>
<section class="col-md-2"></section>
</section>
</section>
I removed the css classes and original names and PHP code to facilitate viewing
Here is sample PHP code, let me know if anything is unclear. I tried to use self-explaining variable names.
<?php
$PAGEBREAK_LENGTH = 1000; // Add a page break every 1000 characters.
$lengthTracker = '';
while ($row = odbc_fetch_array($res)){
$lengthTracker .= $row['article'];
$lengthSize = strlen($lengthTracker);
if ($lengthSize > $PAGEBREAK_LENGTH) {
echo '<div class="page-break">This is a page break</div>';
$lengthTracker = ''; // Reset length tracker since we just added a break
}
echo '<div class="article">';
echo $row['article'];
echo '</div>';
}
?>
If you include the if ($lengthSize > $PAGEBREAK_LENGTH) before echoing the article, you will tend to include page-breaks "more often." If you include the if statement after the article is echod, you will have page-breaks less often (so you'd have potentially bigger blocks of text).
Experiment with both ways to see which style you prefer, since you (presumably) can't include page breaks mid-article.
I found out that my problem was caused not by the faulty page breaks, but I had negative margins in an element, that messed the entire way page breaks work, by removing that, it worked normally.
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; ?>
So I was just wondering if it was considered bad practice to open and close PHP statements, and let me explain what I mean. I know I can make variables at the beginning of my code but I like to group stuff together.I'm not sure if making one big PHP statement with all my variables is better / worse / same as opening and closing PHP statements similar to the example below.
<html>
<head></head> <---- HTML STUFF
<?php
(php stuff where connection to mysql db goes and other variables and errors)
?>
<body>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
</body>
<html>
BTW the php variables I'm talking about are specific select statement from the DB.
ACTUAL CODE: or should select statements be at beg or sep file?
<table>
<tr>
<td align="left" width="200px">
Cover: Original Total
</td>
<td width="200px" align="center">
<?php
$original = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"original\"";
$orig_con = mysqli_query($comic_connect, $original);
$orig_total = mysqli_num_rows($orig_con);
echo $orig_total;
?>
</td>
</tr>
<tr>
<td width="200px" align="left">
Cover: Variants Total
</td>
<td width="200px" align="center">
<?php
$variants = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"variant\"";
$variant_con = mysqli_query($comic_connect, $variants);
$variant_total = mysqli_num_rows($variant_con);
echo $variant_total;
?>
</td>
</tr>
<tr>
<td align="left" width="200px">
Cover: Baby Totals
</td>
<td width="200px" align="center">
<?php
$baby = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"baby\"";
$baby_con = mysqli_query($comic_connect, $baby);
$baby_total = mysqli_num_rows($baby_con);
echo $baby_total;
?>
I'm assuming the repeated <html> tags in your example are just placeholders and would actually be <div>s and other elements making up the actual content of the page.
Your example is what's commonly called "spaghetti code" because it can quickly turn into an unmaintainable mess because you can't clearly see an overview of the HTML, nor can you see all the PHP code in one place.
The main thing to keep in mind is separating application logic (such as your database queries) from presentation (HTML and presentation logic like looping over an array to display it as an HTML list).
At the very least you'd want to put the main PHP code at the top of the file like you said, but it would be much better if it was in a separate file.
P.S. Any beginner book on PHP will discuss this in detail.
I have a table inwhich I also use php's echo to display data inside td elements. Now I have another condition I need to apply for it as whenever the condition is satisfied the table is displayed or else it is removed/turned off.
<?php if(condition)
{
<table>
</table>
}
?>
I would like to know which way to do this best and could help me not to type in " ' " at the beginning of each element's square bracket throughout the whole table ?
UPDATE
It's very simple to geeks and all the talented coders.
if the condition is satisfied then display the table, otherwise don't
display anything in the view. Please remember also that inside my table I also use echo > $data etc to display table's data elements.
<?php
if (condition)
{
?>
<table>
</table>
<?php
}
?>
I do not understand the second part of the question (about the single quotes).
You can use any one method out of given two:
First:
<?php if(condition)
{
?>
<table>
<?php //some statement?>
</table>
<?php
}
?>
Second:
<?php if(condition) : ?>
<table>
<?php //some statement?>
</table>
<?php
endif;
?>
if this is what you mean..
<?php if(condition): ?>
<table>
...
</table>
<?php else: ?>
... do something else in html TAG
<?php endif; ?>
if you dont want to use quotes then yes the Logans answer is the best
Else you can use print or echo
All the best