Create a table using foreach() - php

I have following PHP code contain 2 foreachs
echo "<table class='table table-bordered'>";
foreach($resultOld as $key=>$value)
{
foreach ($value as $key1 => $subjects) {
$checked = $subjects;
echo "<tr><tr class=\"".$subjects."\">$key1
<input type='checkbox' class=\"".$subjects."\" value='checked' name=\"".$key1."JAN\" $checked/> </tr>
</tr>" ;
}
}
echo "</table>";
$resultOld is a fetchAll(PDO::FETCH_ASSOC) output and it contains a two dimensional array. $subjects will return 661 words from the database which means the $resultOld array have 661 elements. And after every 12 cells I want to start a new line (tr). That means I need 55 rows in the table. How to achieve this using PHP?

If you want a new row after every 12 records, you need to use a counter and check the count -
$counter = 1;
echo "<table class='table table-bordered'>";
echo "<tr>"; //start the first row
foreach($resultOld as $key=>$value)
{
foreach ($value as $key1 => $subjects) {
// if the 13th cell, end last row, and start new row
if ($counter%12==1){
echo "</tr><tr>";}
$checked = $subjects;
echo "<td class=\"".$subjects."\">$key1
<input type='checkbox' class=\"".$subjects."\" value='checked' name=\"".$key1."JAN\" $checked/> </td>" ;
// increase counter
$counter++;
}
}
echo "</tr>"; // end last row
echo "</table>";

First, note that your HTML structure is wrong. I recommend thinking about this is a little more steps. Perhaps layout a single row <table> HTML structure for reference between slicing it up into PHP
Here's an example:
<table class="...">
<tbody> <!-- I recommend using the tbody tag -->
<tr>
<td>...</td>
</tr>
</tbody>
</table>
There's three basic things to think about:
The Table Body
The Row
The Columns (ie. Cells)
Step 1 is to print the table body. You're doing fine here:
echo '<table class="table table-bordered">';
echo '<tbody>';
//...
<echo '</tbody>';
echo '</table>';
Step 2 is to loop through your rows
echo '<table class="table table-bordered">';
echo '<tbody>';
// Loop Through Rows
foreach($resultOld as $key=>$value)
{
echo '<tr>'; // start a new row
// ...
echo '</tr>'; // end a row
}
<echo '</tbody>';
echo '</table>';
Step 3 is to loop through each column or cell of the table:
// STEP 1
echo '<table class="table table-bordered">';
echo '<tbody>';
// STEP 2
// Loop Through Rows
foreach($resultOld as $key=>$value)
{
echo '<tr>'; // start a new row
// STEP 3
foreach ($value as $key1 => $subjects) {
$checked = $subjects;
// Start a new column/cell
echo '<td class="' . $subjects . '">';
// Print cell contents
echo $key1;
echo '<input type="checkbox" class="' . $subjects . '" value="checked" name="' . $key1 . 'JAN" '. $checked . '/>';
// End column/cell
echo '</td>';
} // END STEP 3
echo '</tr>'; // end a row
} // END STEP 2
echo '</tbody>';
echo '</table>';
// END STEP 1
Some notes on your code:
You're printing 2 Table rows instead of printing a table row and a table column (ie: <tr><tr> instead of <tr><td>;
You need to print the row inside the first loop, not the second loop.
The second, nested, loop prints out your 2nd dimension or columns.
For me, I like to use single quotes (') with printing HTML. I do this because I use double quotes (") for HTML attributes. This allows me to avoid having to escape the double quote character and getting a hard to read '\""' situation, which can cause simple syntax bugs.
Also when running into problems printing HTML, braking the HTML into multiple echo/print statements can help you structure your code and troubleshoot the problems. Once it's working you can go back and refactor them into a single echo statement, however the performance difference would probably so minor that it's not worth the time.
I hope that helps!

Related

Json to table php empty records

I want display json output to html table, but the table have much empty records. (photo below)
<?php
$json2=file_get_contents("****" . $row["Kenteken2"]);
$data2 = json_decode($json2);
if (strpos($data2[0], 'model') !== false) {
echo '<h4>Zelfde serie voertuigen</h4>';
// Open the table
echo '<table class="GeneratedTable">';
echo '<thead><tr><th>Niet DB</th><th>In DB</th></tr></thead><tbody><col style="width:50%" span="2" />';
// Cycle through the array
foreach ($data2 as $vrt) {
// Output a row
echo '<tr>';
echo '<td>'.$vrt->model .'</td>';
echo '<td>'.$vrt->model2 .' '.$vrt->dienst . ' ' . $vrt->bijzonderheden .'</td>';
echo "</tr>";
}
// Close the table
echo "</tbody></table>";
}
?>
result:
If you want 1 table:
I would create a foreach to create 2 different arrays $neit_db[] and $in_db[]
I would then do a while loop so that until both arrays are empty, I would ping pong between both of them $neit_db[0], then $in_db[0] for each 'row', etc.
If you want 2 tables:
I would create a foreach to create 2 different arrays $neit_db[] and $in_db[]
I would while loop to loop through each array individually for each table that you've put next to each other.

PHP table alignment is not correct inside foreach Loop

I want to display Array data in a table with 3 columns in a row using foreach loop with a condition.
Coding
$value[]='a';
$value[]='b';
$value[]='c';
$value[]='d';
$value[]='e';
echo '<table width=30% border=1>';
echo '<tr>';
$counter=1;
foreach($value as $key){
if($counter>=3){ // if there is more than 3 elements, go to next Row
if($counter%3==0){ // when the Array hit 3th,6th,9th,12th.... element
echo '</tr><tr><td>';
echo $key;
echo '</td>';
}else{
echo '<td>';
echo $key;
echo '</td>';
}
}else{
echo '<td>';
echo $key;
echo '</td>';
}
$counter++;
}
echo '</tr>';
echo '</table>';
I double check the coding and didn't manage to find the error.... my output is the bottom of the image. However, the correct one should be top of the image. Please take a look at the photo
Anyone know what's wrong with my coding?
Change modulas condition with
if($counter % 3 == 1)
and you will get what you desire
You have "if counter >= 3" so you are hitting that condition on your 3rd element, not AFTER your third element.
Change the initialization of your counter to $counter=0;

php echo table with while loop

I am creating a table and want it laid out a certain way and have to retrieve the data from the DB. I am trying to get it set up where it has the usernames across the top example...
Jim Chris Allen Rick
7 8 4 5
my code looks like this and I have been messing around with it for hours and cant figure out why I cant get it set up how I want. Any help would be appreciated. Its a while loop.
while ($pickresults= mysql_fetch_assoc($picksquery)) {
//first row
echo '<th> '.$pickresults['username'].' </th> ';
echo ' <td> '.$pickresults['firstgame'].' </td> '; }
First off, you should learn the HTML code for tables. Your code is putting a Table Header (th) next to a normal column item (td). You need to loop through the headers first then next row loop through the column items or build the strings to echo out.
$headers = $col = "";
while($pickresults= mysql_fetch_assoc($picksquery)){
$headers .= "<th> {$pickresults['username']} </th>";
$col .= "<td> {$pickresults['firstgame']} </td>";
}
echo "<table><tr>$headers</tr><tr>$col</tr></table>";
Your structure is creating a TH then a TD and then a TH and then a TD etc.
This isn't how you create a table, you first need to make the four TH's and THEN you can make the four TD's.
Edit: Marko D has supplied the code to explain what I mean.
First collect table header and body, and then output them. The way you were doing, html was like this, I guess it's easy to see what is wrong with html
<th>name</th>
<td>value></td>
<th>another name</th>
<td>another value</td>
What you need is this:
$td = '';
$th = '';
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$th .= '<th> '.$pickresults['username'].' </th> ';
$td .= '<td> '.$pickresults['firstgame'].' </td> ';
}
echo '<table><tr>' . $th . '</tr><tr>' . $td . '</tr>' . '</table>';
You need to write all usernames in <th>-tags.
I'd put it in an array first, and from the array into the table...
while ($pickresults= mysql_fetch_assoc($picksquery)) {
$picked[]=$pickresults;
}
echo "<table><tr>"; // create table and 1st row
foreach ($picked as $pick) {
echo "<th>{$pick['username']}</th>"; // create 1st line headers
}
echo "</tr><tr>"; // close 1st row and open 2nd
foreach ($picked as $pick) {
echo "<td>{$pick['firstgame']}</td>"; // create 2nd line...
}
echo "</tr></table>"; // close 2nd row and table

Adding extra table row

I'm stuck and can't figure this out.
I have this piece of code which is basically generating a table taking data from SQL cursor.
I need to add one extra table row <tr> (which will be filled with additional info) after each row. I've tried putting the new row in several places, but there is never any output data for it. This is someone else's code that I'm trying to modify.
$top_i=min($pagesize-1,$numrows-$start);
for($i = 0;$i<=$top_i;$i++) {
if (($i%2)==1)
echo "<tr class='saraksts_row0'>";
else
echo "<tr class='saraksts_row1'>";
$res=mssql_query("fetch absolute ".($start+$i)." from saraksts_cursor ");
$row=mssql_fetch_array($res);
$itemp = 0;
foreach($fields as $field) {
$key = $field[0];
if($field[2]) {
eval($field[2] );
}
$itemp++;
$val = ($row[$key] == "") ? " " : $row[$key];
// Get rid of right and left border, set topmost border
$st="";
if ($itemp==1)
$st.="border-left-style:none;";
if ($itemp==$numfields)
$st.="border-right-style:none;";
if ($i==$top_i)
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
$itemp = 0;
echo "</tr>\n";
}
The place where you want to add the extra row is after closing the first row and before the iteration moves to the next one. Note, it appears that you are doing some styling based on whether the row is odd or even. If you want this new row to have the same styling, I suggest you store the class you're applying to the preceding row so that you can also apply it to this row.
echo "</tr>\n";
echo "<tr><td>...</td><td>...</td></tr>\n"; /* Add the new row here */
}
...
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
//Here we go
echo '<td style="blah">'.$yourotherinfo.'</td>';
$itemp = 0;
echo "</tr>\n";

PHP/MySQL Output Data in TD's

How would I go about imposing a restriction on the number of HTML table columns when querying the database.
For example, I have a MySQL table with the following values:
myTable:
id color
1 red
2 blue
3 green
4 pink
5 purple
And when I run my query, instead of showing all rows in traditional table rows, e.g.
<table>
<?php
while {
echo "<tr><td>$row['color']</td></tr>;
}
?>
</table>
Instead, I would like to impose something where, every three td's, a new tr is created.
For example, it would output something like this:
<table>
<tr>
<td>red</td>
<td>blue</td>
<td>green</td>
</tr> <-- Notice how after 3 columns, a new table row is created.
<tr>
<td>pink</td>
<td>purple</td>
</tr>
</table>
Any way to achieve this?
In order to achieve this, you can use a combination of a counter and a modulus (%) operator:
<table>
<?php
$count = 0;
while($row = mysql_fetch_array($results)) {
$outputTr = ($count % 3) == 0;
if($outputTr) echo '<tr>';
echo '<td>' . $row['color'] . '</td>';
if($outputTr) echo '</tr>';
$count++;
}
?>
</table>
To achive this, put in a simple counter that resets every 3 table datas.
<?php
echo "<table><tr>";
$count = 0;
foreach($data as $key => $color)
{
if($count == 3)
{
$count = 0;
echo "</tr><tr>";
}
$count++;
echo "<td>".$color."</td>";
}
echo "</tr></table>";
?>

Categories