Making a 2 coloumn table with PHP without 'echoing' so much - php

I am working with PHP and My SQL to get data from an SQL database and show it in 2 columns.
I have figured out how to do it with the code as below. However I am working with a complex HTML template and don't want to echo every single HTML line to get it work - It will be very complicated to read and fix if there is an issue!
<table>
<?php
$i = 0;
while($row = $result->fetch_assoc()) {?>
<?php if (++$i % 2 != 0) echo "<tr>";?>
<?php echo "<td>" .$row['fname']."</td>"; ?>
<?php if ($i % 2 == 0);
} if ($i % 2 != 0); ?>
<td></td></tr>
</table>
I have simplified the template as below. Here I am 'echoing' within the HTML which I find easier to read and understand:
<div class=container>
<div id="fname"><a>First Name:</a><?php echo $row['fname'];?></div>
<div id="website"><a>Website:</a><?php echo $row['website'];?></div>
</div>
To summarize, is it possible to take my data from the database and show it in 2 columns without having to echo every single HTML line. Keeping my HTML structure similar to the above?
The column layout I am try to achieve is as below:
1 | 2
-----
3 | 4
-----
5 | 6
-----
I have not been able to find an example anywhere! Thanks!

There are advantages to writing HTML out in PHP script and there are also advantages to breaking into PHP from your HTML script. It really just depends on the circumstances.
For example if I am writing html that is generated from loops of has alot of variable inputs I will write the HTML inside the PHP. However, If I am writing a big chunk of HTML with only a few variables I will break into PHP from the HTML.
It really just depends on the circumstances.
That being said, when writing HTML from inside of PHP I will break it down and concatenate the HTML as much as possible. That way I am not breaking in and out of PHP to get the task accomplished. The more you code the easier that will get.
Below is how I would write your code. Notice I never broke in and out of PHP.
echo
'<table>';
$i = 0;
while($row = $result->fetch_assoc()) {
echo
'<tr>';
echo
'<td>' . $row['fname'] . '</td>' .
'<td>' . $row['lname'] . '</td>';
echo
'</tr>';
}
echo
'</table>';
Hope this helps.

You could do something like this in PHP, just another very simple option.
$str = '';
while($row = $result->fetch_assoc()) {
$str .= '<tr><td>'.$row['value1'].'</td><td>'.$row['value2'].'</td></tr>';
}
I don't know all the correct keys in the $row, but I think you get the idea.
And than the HTML would be like this:
<table>
<?php echo $str; ?>
</table>
Just a little hint. You can google on a MVC construction. This stands for Model View Controller and it is in my opinion the best way to keep your code organised.

Related

PHP: Which is more efficient: a concatonated return variable, or returning each line individually?

I have a sytem where I want to build an HTML table in PHP from data retrieved from a databse.
I've previously used two different methods for creating the HTML and echoing it.
Building a return variable, and echoing at the end of the PHP script:
<?php
$data['category']['parts']; // format of the data
$retval = '<table>';
foreach($data as $category) {
$retval .= '<tr>';
foreach($category as $data) {
$retval .= '<td>'.$data.'</td>'
}
$retval .= '</tr>';
}
$retval .= '</table>';
echo $retval;
The other method is to echo each line as the code comes to it:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>'.$data.'</td>'
}
echo '</tr>';
}
echo '</table>';
Which of the two methods is more efficient, in terms of processor/memory usage, and also for processing speed?
Is there actually a real difference, rather than just a question of style?
My shot is: whatever you find more readable. Impact on performance is so small that probably you won't see any difference.
However, if you really care, echo should be faster (nothing better than a performance test on your specific scenario) because string concatenation will resize retval multiple times (and this will impact performance).
Even better you should avoid concatenation also in your echo:
<?php
$data['category']['parts']; // format of the data
echo '<table>';
foreach($data as $category) {
echo '<tr>';
foreach($category as $data) {
echo '<td>', $data, '</td>';
}
echo '</tr>';
}
echo '</table>';
Do you want to do better? Just construct your own string builder object (but, honestly, gain is so small that you should seriously consider if worth your effort).
If you want to use kind of a templating to generate your page, I would rewrite your code to something like this.
(this can be in a dedicated file, and just included to display output)
<?php
$data['category']['parts']; // format of the data
?>
include ('templates/theFileIWantToShow.php');
---- snip files here. Processing above, template bellow.
<table>
<?foreach($data as $category):?>
<tr>
<?foreach($category as $data):?>
<td><?=$data?></td>
<?endforeach;?>
</tr>
<?endforeach;?>
</table>
This would offer (imho) best readability when it comes down to large html pages with only a few wildcards.
Advantages:
You get clean html with only a few spots of php in between
You can easily replace the template files without touching the generating code
you can reuse templates. Providing direct output and/or building strings is a mess, when it comes down to reuse the same html-markup for a certain element over and over.
Note that this requires shorttags to be enabled in your php.ini for PHP < 5.4.0.

Creating a variable template to display a database content

I'm working on a database website currently and part of the project is to display the content of a database in a custom form using pixels to position the various fields.
I am however having trouble getting the code to work as the way I'm creating the form doesn't seem to work in a php tag, but It requires a WHILE loop in order to continue running until the database field is empty.
I'm only including the relevant code section so as to not clog up the post, all my coding is segmented so I can isolate bugs.
<?php
$usernameh = 20;
$units = "px";
for ($x=0; $x<=2; $x++) {
$pix=$value . $units;
<div style="position:absolute;left:10px;top:20px;width:100px;height:20px;z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>
$value += 150;
}
?>
The idea is to substitute the 20px on the first line of the divcommand with $pix so that with each iteration the value increases by a set amount and separates out the entries.
I'm very new to php coding, as in only really started 2 weeks ago. I'm sure there is a simple solution to this but I'm not sure what question to ask Google to get the response I'm after.
I hope my problem makes sense. The database is in MySQL but all that is fine, its just the formatting I'm struggling with. Even without using a variable in the formatting code the script crashes while the php tag is in effect.
Can anyone offer any advice on where my problem is or suggest another alternative to this.
Thanks!
You need to break out of PHP ?> before HTML and then switch back to PHP <?php before more PHP code
$value = 20;
$units = "px";
for ($x=0; $x<=2; $x++) {
$pix = $value . $units;
?>
<div style="position:absolute;left:10px;top:<?php echo $pix ?>;width:100px;height:<?php echo $pix ?>;z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>
<?php
$value += 150;
}
Or for the HTML you can echo it from PHP:
echo '<div style="position:absolute;left:10px;top:' . $pix . ';width:100px;height:' . $pix . ';z- index:5;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:15px;">Field Name:</span></div>';

Setting a CSS element class in PHP

I'm trying to modify a bit of PHP code to get it to assign a unique CSS class to the elements it creates as it cycles through its loop. Theoretically, I'm just trying to take a "name" that's echoed to the screen and assign that as a class to a element that's created next... Here's the intitial relevant code loop:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Simplistcally, I'm trying to get the string that's echoed by $exam->name to be assigned to the class of that <tr> element. Something like
<tr class="<?php echo $exam->name;"><td><?php echo $exam->name;?></td></tr>
Although I'm sure I'm handling the quotes or syntax improperly (at least, anyway, it doesn't end up assigning the class to the <tr>.
It will help if you stop going in and out of PHP so much, it will probably be easier to read this way:
<?php
foreach($my_exams as $exam){
if($exam->is_taken){
echo '<tr class="'.$exam->name.'"><td>'.$exam->name.'</td></tr>';
}
}
If you want to do double quotes, you need to escape them when you want to echo them, but then you can use a variable without concatenating a bunch of strings. (Once you are using objects/arrays it helps to surround each variable with {})
echo "<tr class=\"{$exam->name}\"><td>{$exam->name}</td></tr>";
Reference: http://us2.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
<tr class="<? echo $exam->name ?>"><td><? echo $exam->name ?></td></tr>
Others have answered this pretty much the same way I am about to, but I want to add this to explain the issue. And why this is not a “stupid” question, but more of a bizarre byproduct of the way that some CMS system mix HTML & PHP within their templates. In short: They format the template as nice HTML to make it seem clean & easy for non-coders, but in doing so their mixing of inline-PHP makes PHP coding seem more difficult than it is. Meaning this code:
<?php foreach($my_exams as $exam):
if(!$exam->is_taken) continue;?>
<tr><td><?php echo $exam->name;?></td></tr>
<?php endforeach;?>
Can easily be this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo '<tr><td>'
. $exam->name
. '</td></tr>'
;
}
}
?>
Which is now easier to parse from a programming standpoint, so you can now do this:
<?php
foreach($my_exams as $exam) {
if ($exam->is_taken) {
echo sprintf('<tr%s><td>', ' class="' . $exam->name . '"')
. $exam->name
. '</td></tr>'
;
}
}
?>
What I did there is use sprintf to place ' class="' . $exam->name . '"' into the ''. The %s means that is a string that should be placed there, and the string is what comes after the comma in the sprintf statement. I find this much easier to code, test & debug. But in general, the key to making PHP coding easier is to just use straight PHP when any logic needs to be placed in the context of HTML.

I want do style tables, but it doesn't work in PHP

I want to create a site, which displays a lot of records from a database. To make it more reader-friendly, I want to use a styling. One record is white background, the next blue, the next hhite again.
So I tried this:
<?php while ($info = mysql_fetch_array($data)){
PRINT "<tr>";
PRINT "<td>" .$info['articlenr']. "</td>";
PRINT "<td>" .$info['stock']. "</td>";
PRINT "</tr>";
PRINT "<tr>";
PRINT "<td bgcolor=#0066FF>" .$info['articlenr']. "</td>";
PRINT "<td bgcolor=#0066FF>" .$info['stock']. "</td>";
PRINT "</tr>";
}
?>
This works for the view, but the problem is, the blue record is the same as the white, not the next one, it just doubles the record and make it another color.
How can I do this right?
Use :nth-of-type(even) to get even/odd combination of color's.
Here is a demo example:
html:
<table>
<tr><td>item1</td>
</tr>
<tr><td>item2</td>
</tr>
<tr><td>item3</td>
</tr>
<tr><td>item4</td>
</tr>
</table>
css:
tr:nth-of-type(even) { background-color: #0066FF; }
Demo
If you want to do this in PHP, you could do it like this :
<?php
$iter = 0;
$color1 = 'red'; //can se hex code too, like #0066FF;
$color2 = 'blue';
while ($info = mysql_fetch_array($data))
{
echo '<tr style="background-color:'.( ($iter%2==0) ? $color1 : $color2).';">';
// rest of the printing stuff
$iter++;
}
?>
Statement
($iter%2==0) ? $color1 : $color2
does this : it asks the question whether iterator (or row number) is even. If yes, the it takes color1. If not (row is uneven) it takes the second color.
PHP Smarty is good for doing this kind of stuff (iterating over colors and styles), but it may be difficult for beginners.
Please go through this links:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started
http://css-tricks.com/complete-guide-table-element/
Including CSS in .php file
Can I offer some advice on your code? Your approach mixes PHP and HTML in a way that makes it difficult for your development environment to parse your HTML, and you can achieve the same with less keystrokes! Consider this approach instead:
<?php while ($info = mysql_fetch_array($data)): ?>
<tr>
<td><?php echo $info['articlenr'] ?></td>
<td><?php echo $info['stock'] ?></td>
</tr>
<?php endwhile ?>
Changes I've made:
Removed the duplicate row
Rendered everything in HTML mode, and opened PHP tags just for PHP code
Switched the loop to the colon form, which is often thought to be clearer in templates. Do carry on using the brace approach, however, in large chunks of code (e.g. classes)
Written PHP keywords in lower case
Used echo rather than print
Combine this with Joke_Sense10's answer for a full solution.

How to append html tags every three rows of a table that is being dynamically generated using Jquery

Is there a way I can use Jquery to insert '' tags after every three dynamically generated table cells so that I end up with a dynamic three column table?
Please excuse my lack of knowledge, I'm literally trying to write my first jquery script ever, so I know absolutely nothing. I know php and I have a table that has a loop within it that is dynamically creating <td></td> with the information inside each tag. In other words it is dynamically creating the table cells within a static <tr></tr> tag. The problem is that it keeps outputing tables without breaking them up into rows which leaves me with a bunch of columns. I've read other articles on this but none seem to have the exact same problem as I do, and I am still struggling to understand how to write custom Jquery code.
The php code is very long and is full of numerous if statements and other functions so I'm not going to post it here but just to make it a little simpler, I made miniature mockup of what I'm trying to do.
<table id="mytable" width="266" border="1" cellspacing="10" cellpadding="10">
<tr>
<?php
$x=0;
while (have_products($x)) {
echo '<td>' . somelongassfunction() . '</td>';
$x++;
if (fmod($x,3) == 0) {
echo '</tr><tr>';
continue;
}
if ($x==20){
echo '</tr>';
}
}
function somelongassfunction(){
return 'Hello';
}
function have_products($a){
return $a<=20;
}
?>
</table>
This code loops and dynamically adds table cells up to the limit I give it which would represent my database items. Every three rows, it adds either a <tr></tr> or just a </tr> depending on whether the loop continues or not. This creates a 3 column table. I can't apply this code for my script because it is a very long and complex script that has a lot of if statements and functions. There is no way of doing it like this without breaking the code or having to rewrite everything from scratch all over again.
Is there anyway I can append the tr tags dynamically with Jquery and how would I go about to applying this to?
The jQuery approach would be to loop through all of the tabs, and add them to newly created tags, which themselves are added to the html of the table. Roughly:
var thisCount=0;
var currenttag="<tr />";
var table=$("table");
$("td").each(function ()
{
if(thiscount==2)
{
table.appendChild(currenttag);
thisCount=0;
currenttag="<tr />";
}
currenttag.appendChild(this);
}
( this is just to give an idea, not intended as a formal JQ answer. If anyone wants to edit it so it works fully, feel free ).
You can use a selector to select every third row:
$('#table_id > tr:nth-child(3n)').whatever_function()
However if you are trying to append end /tr tags, try doing it in PHP using a counter that resets itself (this code should get you started):
echo "<tr>";
$x = 0;
$y = 0;
while (have_products($x)) {
echo '<td>' . somelongassfunction() . '</td>';
$y++;
if ($y == 3) {
$y = 0;
echo "</tr><tr>";
}
$x++;
}
echo "</tr>";

Categories