Skip to content Skip to sidebar Skip to footer

How Do I Create Tables Dynamically From User Input?

Want I want to do is create a table with what the user input for rows and columns, but I don't understand how to do this. Ex. User inputs: number of rows: 4 number of columns: 5

Solution 1:

Once you get your input data with GET or POST method and then you assign them to variables like $rows and $cols. you can do this

$cols = 5;
$rows = 2;

$table = "<table>";
for($i=0;$i<$rows;$i++)
{
   $table .= "<tr>";
      for($j=0;$j<$cols;$j++)
         $table .= "<td> Content </td>";
   $table .= "</tr>";
}
$table .= "</table>";


echo $table;

Solution 2:

In Php get the input values and and generate table using loop... here is a complete code ... check it..

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic Table</title>
</head>
<body>
    <form action="" method="get">
        ROWS <input type="text" name="rows"> COLUMNS <input type="text" name="cols"><input type="submit" value="Generate">
    </form>
    <?php
    // Just a check you can change as your needs
if(isset($_GET['rows'])){

$rows=$_REQUEST['rows'];
$cols=$_REQUEST['cols'];
echo '<table border="1">';
for($row=1;$row<=$rows;$row++){
    echo '<tr>';

    for($col=1;$col<=$cols;$col++){
        echo '<td> sample value </td>';
    }

    echo '</tr>';
}
echo '</table>';

}


    ?>
</body>
</html>

Solution 3:

Copy and paste into a php page, place the column and lines in text fields click the Create Table button, keep testing and looking at the source code that one day you'll understand.

<?php
    $table = '';
    if ($_POST) {
        $table .= '<table border="1">';
        for ($i = 0; $i < $_POST['qty_line']; $i++) {
            $table .= '<tr>';
            for ($j = 0; $j < $_POST['qty_colunn']; $j++) {
                $table .= '<td width="50">&nbsp;</td>';
            }
            $table .= '</tr>';
        }
        $table .= '</table>';
    }
?>
    <form action="" method="post">
        <table border="0" width="200">
            <tr>
                <td width="80"><label>Column</label></td>
                <td width="120"><input type="text" name="qty_colunn"></td>
            </tr>
            <tr>
                <td><label>Line</label></td>
                <td><input type="text" name="qty_line"></td>
            </tr>
            <tr>
                <td colspan="2" align="right"><input type="submit" value="Create Table"></td>
            </tr>
        </table>    
    </form>
    <br />
    <br />
<?php
    echo $table;
?>

Post a Comment for "How Do I Create Tables Dynamically From User Input?"