0

我有一张表格,上面有一排国家、名字等

我还有一个表格,每行都有处理

我需要在同一页面上提交表格

如何到达同一页面上同一张表的下一行

我是使用 while 还是 foreach,我在哪里放置结束语}还是有其他方法?

4

1 回答 1

0

Ok i made a start for you. I think you want to list all the rows from the db into an HTML table with an form at the bottom to add a new row to the db, right?

If so, then you can do it with this single PHP page code. Please note that i'm not considering any security for safe queries! You can find more about that on the Internet.

<?php
    $DB_NAME = 'DATABASE_NAME';
    $DB_HOST = 'DATABASE_HOST';
    $DB_USER = 'DATABASE_USER';
    $DB_PASS = 'DATABASE_PASSWORD';

    // CONNECT TO THE DATABASE
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    //form submit?
    if(isset($_POST['save'])) {
        //INSERT QUERY
        $q = "INSERT INTO `your_table`(`field1`, `field2`, `field3`) VALUES ('" . $_POST['field1'] . "', '" . $_POST['field2'] . "', '" . $_POST['field3'] . "')";
        $mysqli->query($q) or die($mysqli->error.__LINE__);
    }

    //get all items from db (also the new row)
    $query = "SELECT * FROM `your_table`";
    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);

    //build first part of table
    echo '<table>
            <thead>
                <th>
                    <td>Your field1</td>
                    <td>Your field2</td>
                    <td>Your field3</td>
                </th>
            </thead>
            <tbody>';

    //create rows
    if($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo '<tr>
                    <td>' . $row['field1'] . '</td>
                    <td>' . $row['field2'] . '</td>
                    <td>' . $row['field3'] . '</td>
                 </tr>';    
        }
    } else {
        echo '<tr><td colspan=3>NO RESULTS</td></tr>';  
    }

    //close table
    echo '      </tbody>
          </table>';

    // CLOSE CONNECTION
    mysqli_close($mysqli);
?>

<!-- the form -->
<form action="#" method="POST">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="text" name="field3" />

    <input type="submit" name="save" value="save" />
</form> 

Hopes this helps!

于 2012-11-30T08:50:37.077 回答