Json to table php empty records - php

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.

Related

Populate 2 column HTML table with a single PHP result set

Please forgive me as I am beginner in PHP.
I am trying to populate 2 two column table with inventory information. With my current code, I have the below image:
I would like to have two stores next to each other in this table. i.e Store Number 2 and Store Number 7 on the table row in the table, then Store 10 and 11 on the same row, and so on. Below is the code I am using so far to achieve this:
global $wpdb;
$result = $wpdb->get_results(
$wpdb->prepare( "
SELECT STORE_NAME,REPLACE(STORE_NAME, ' ', '-') as STOREURL, INVENTORY, STORE_NUMBER FROM StoreInventory
WHERE SKU = %s",
$product_sku
)
);
if ($result){
echo '<table class=\'inventory\'>';
foreach($result as $row) {
echo '<tr><td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td></tr>';
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}
The problem I am having is that I am looping through the record set row by row, and adding the data to each row. I have attempted to have a loop inside a loop, which will not give me the correct results.
Is it possible to split the result set into two multi-dimensional arrays and loop through each one separately then add them to the table? Can I call out a specific row with a counter within the loop?
Any advise or direction would be a great help.
A relatively simple approach would be to create a dummy variable to store the column. EX:
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</tr></table>';
Final answer based on ARubiksCube's answer:
if ($result){
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td \' width=\'50%\' ><div><a href=\'https://shopliquornl.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>' . $row->STORE_NAME . '</a><br/>' .$row->INVENTORY. ' on hand</div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}

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;

Can I display query results without naming columns?

Is there a php or html code to dynamically generate a table.
query :
"SELECT * FROM table1;
Can I display this grid of info without any specifics.
IF there are 4 rows and 4 columns I want the table to be that size; if 5x5 than that.
It seems like this should be possible, but all code I can find wants me to specify names or columns.
Yes. There are a couple different ways to do this, but for illustration I will assume that the result of your query is stored in a variable called $results, which is simply a multidimensional array that you can loop through using a double foreach to dynamically produce your table.
echo '<table>';
foreach ($results as $row) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';
OR if you don't have a $results array and are instead getting query results and building the table at the same time, something like this might be more appropriate for your needs:
echo '<table>';
while ($row = mysqli_fetch_array($query)) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';
echo'<table>';
while($row = mysql_fetch_array($result))
{
echo'<tr>';
echo '<td>'.$row[colname].'</td>';
echo '</tr>';
}
echo'</table>';

Create a table using foreach()

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!

PHP: Creating big HTML-table efficiently

I'm making a HTML table based on certain information in my MySQL database. The tables I need from the database hold the data for rows (rowid, rowname), columns (columnid, columnname) and cell data. A table, that links IDs from rows and columns together (cellid, rowid, columnid, somedata).
The table looks something like this:
__________| column1 | column2 | column3 | ...
row1 | somedata | somedata | |
----------|----------|----------|----------|-----
row2 | somedata | | somedata |
----------|----------|----------|----------|-----
... | | | |
My approach was to use several nested foreach loops, something like this:
$rows = new Rows(); //These objects are containers for objects
$columns = new Columns(); //that hold some of the database data.
$alldata = new Alldata(); //MySQL queries within these objects are irrelevant, I think. They already get the relevant data
$count = count($alldata);
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
foreach ($alldata->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) { //If the column has data the related to the row
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) { //if loop couldn't find any entries, it prints an empty cell
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
Bruteforcing, obviously this is not very efficient method when there are several hundred rows of data on any table in the database and I don't like this. Any ideas how to make this more efficient? Is there better way of creating a table like I need?
EDIT:
Pondering about this problem for a week has finally given me some answers. It was so simple!
I did a slight modification to my Column object class. Previously, my code went through all possible entries on celldata table in the database. Now Column object gets an array of celldata where columnid's match and I can do the comparison using only that data.
$rows = new Rows();
$columns = new Columns();
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
$count = count($column->getAlldata());
foreach ($column->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) {
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) {
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
Much faster, although still bruteforcing but there's less amount of data to go through. Of course, now the problem is that Column objects may do quite a lot of MySQL queries, depending on how many Columns there are.
If you ensure that the data fetched from MySQL is correctly ordered in $alldata by joining the tables and specifying an ORDER BY clause in your query:
SELECT data.*
FROM data RIGHT JOIN rows USING (rowid) RIGHT JOIN columns USING (columnid)
ORDER BY rowname, columnname;
Then you only need to output each cell in order:
echo '<table>';
echo '<thead>'
echo '<tr>';
echo '<th> </th>';
foreach ($columns->getColumns() as $column) {
echo '<th scope="col">', htmlentities($column->getColumnname()), '</th>';
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
$data = $alldata->getAlldata();
foreach ($rows->getRows() as $row) {
echo '<tr>';
echo '<th scope="row">', htmlentities($row->getRowname()), '</th>';
foreach ($columns->getColumns() as $column) {
$d = each($data);
echo '<td>', ($d ? htmlentities($d[1]->getSomedata()) : ' '), '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
The best way to solve this would be to rewrite the query for $alldata so that it is in the order you want like eggyal suggested. If you can't do that for some reason, you could iterate through $alldata in the beginning and create a properly indexed array from it. Something like this:
$ordereddata = array();
foreach($alldata as $d) {
$ordereddata[$d->getCID()][$d->getRID()] = $d->getSomedata();
}
Now you can replace your foreach($alldata) loop with this:
if(isset($ordereddata[$column->getID()][$row->getID()])) {
echo "<td>{$ordereddata[$column->getID()][$row->getID()]}</td>";
} else {
echo "<td> </td>";
}

Categories