如何根据用户输入动态创建表


How do I create tables dynamically from user input?

我想做的是创建一个表与什么用户输入的行和列,但我不明白如何做到这一点。

交货。

User inputs:
number of rows: 4
number of columns: 5

这是我想在html格式中显示的行和列。

一旦您使用get或POST方法获得输入数据,然后将它们分配给$rows$cols等变量。你可以这样做

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

在Php中获取输入值并使用循环生成表…这里是一个完整的代码…检查一下. .

<!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>

复制并粘贴到php页面,将列和行放在文本字段中,单击Create Table按钮,继续测试并查看源代码,总有一天你会理解的。

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