首页 > 解决方案 > Creating a PHP table generator with input fields

问题描述

I am making a template generator for work.

The goal of the generator is to create a table, in which you can input unique fields. After inputting these fields into each table cell, a button will be pressed to generate the template.

The problem that I am having is that the input fields are not being given unique names upon being generated. I understand that an array needs to be created for each input field, but am unsure how to do it in this case.

Any assistance would be great.

I have the following code:

<html>
<body>
    <div>
        <p>Enter number of Rows<p>
        <form action="" method="POST">
        <label for="title">Row</label>
        <input type="text" name="numRows" placeholder="Number of Rows">
        <input type="submit" name="submit" value="Generate Table"> 
    </div>

    <div>
        <?php
            if(isset($_POST['numRows'])) {
                $row = $_POST['numRows'];
                $column = 2;

                echo '<form method="POST" name="form_1st_generate" >';
                echo '<table style="border-collapse: collapse; border: 1px solid black">';
                for($tr=1;$tr<=$row;$tr++) {
                    echo '<tr>';
                        for($td=1;$td<=$column;$td++){
                            echo '<td style="border: 1px solid black"><input type="text" name="tableInput[]" /></td>';
                        }
                    echo '</tr>';
                    }
                    echo '</table>';
                    echo '<input type="submit" value="Generate Template" name="submit_form_1st_generate"/>';
                    echo '</form>';
                }

            if(isset($_POST['submit_form_1st_generate'])){
                echo '<br />';
                echo 'Generated Template';

                $row1col1 = $_POST['tableInput[1]'];
                $row1col2 = $_POST['tableInput[2]'];
                echo $row1col1;
                echo $row1col2;
            }
        ?>
    </div>
</body>

标签: phphtmlarrays

解决方案


一个解决方案是输入名称'table-input-'.$tr.'-'.$td并知道行数和列数,您将能够按顺序迭代所有字段:

for ($tr = 1; isset($_POST['table-input-'.$tr.'-1']); $tr++) {
    for ($td = 1; isset($_POST['table-input-'.$tr.'-'.$td]); $td++) {
        //your server-side stuff
    }
}

推荐阅读