在数据库中插入未知数量的输入类型文本php


Insert into database with unknown number of input type texts php

好的,假设我在数据库中有一个未定义的选定行数。我使用while循环,所以输入面积不断增加。我的问题是我如何插入到我的数据库不知道应该插入多少值?我应该使用某种循环吗?

<form method = "POST" action = "save.php">
while($row = mysqli_fetch_assoc($result)){
<input type = "text" name="txtname">
}
<input type="submit" name="btnsubmit" value = "Save">
</form>

在大多数情况下,在MySQL中使用一条Insert语句插入多条记录比在PHP中使用for/foreach循环插入记录要快得多。

让我们假设$column1和$column2是html表单中相同大小的数组。

你可以这样创建查询:

<?php
    $query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
    $query_parts = array();
    for($x=0; $x<count($column1); $x++){
        $query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
    }
    echo $query .= implode(',', $query_parts);
?>

如果有两个记录,查询将变成:

INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data', 'data'),"数据")