插入具有未知数量的输入类型文本php的数据库

时间:2016-09-05 10:59:56

标签: php mysql sql-insert

好的,假设我的数据库中有一些未定义的选定行数。我使用了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>

1 个答案:

答案 0 :(得分:1)

在大多数情况下,使用一个Insert语句插入多个记录在MySQL中要比在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',   '数据')