I want to create dynamic rows and column with the help of PHP and HTML but I am little confused about this code so some help is definitely appreciated.
<table>
<?php
$tr = 0;
foreach ($data as $db_data) {
$tr++;
if ($tr == 1) {
echo "<tr>";
}
echo "<td>";
echo $db_data['id'];
echo "</td>";
}
if($tr == 2){
}
?>
</table>
Scenario is so simple:
Mysql data return 6 no of records from for-each loop the result will be show like this image
Same way the Mysql data return 3 no of records the result will be show like this image
To dynamically add a new column to an HTML table with JavaScript, we can loop through each row and add td elements into them. to add a table with an add column button. to add the addColumn function and assign that as the click handler of the button. In addColumn , we loop through each row with a for-of loop.
First a dynamic HTML Table is created using JavaScript createElement method. The Header Row will be built using the first element of the Array as it contains the Header column text values.
Dynamic columns is a feature that allows one to store different sets of columns for each row in a table. It works by storing a set of columns in a blob and having a small set of functions to manipulate it.
Something like this, maybe
function create_table($data) {
$res = '<table width="200" border="1">';
$max_data = sizeof($data);
$ctr = 1;
foreach ($data as $db_data) {
if ($ctr % 2 == 0) $res .= '<td align="center">' . $db_data['id']. '</td></tr>';
else {
if ($ctr < $max_data) $res .= '<tr><td align="center">' . $db_data['id']. '</td>';
else $res .= '<tr><td colspan="2" align="center">' . $db_data['id']. '</td></tr>';
}
$ctr++;
}
return $res . '</table>';
}
Course, you can modify style of table to fit your needs.
Call it like this:
echo create_table($data);
(example for 7, 4, 3 and 8 id's)
It returns table with same number of rowsin each column if you pass even number of id's or table where last row is merged if you pass odd number of id's into function.
Use % php operator (division remainder) to break rows where you need
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With