Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic create rows and colum with the help of PHP and HTML

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

enter image description here

Same way the Mysql data return 3 no of records the result will be show like this image

enter image description here

like image 494
Query Master Avatar asked Mar 22 '12 11:03

Query Master


People also ask

How do I create a dynamic column in HTML?

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.

Can we create dynamic table in HTML?

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.

What is dynamic column in mysql?

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.


2 Answers

Something like this, maybe

function create_table()

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);

Output

(example for 7, 4, 3 and 8 id's) enter image description here

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.

like image 167
Wh1T3h4Ck5 Avatar answered Oct 16 '22 10:10

Wh1T3h4Ck5


Use % php operator (division remainder) to break rows where you need

like image 44
Artjom Kurapov Avatar answered Oct 16 '22 10:10

Artjom Kurapov