PHP 表单-是否可以将多个输入字段插入到同一个 table_name 中

是否可以将多个输入字段插入到同一个表名中。

我的数据库设计

http://img4.mukewang.com/64a92f070001317801150104.jpg

Php表单年龄表单有五个输入字段


<form action="action.php" method="post">

input1          

<input type="text" name="age[]">

input2

<input type="text" name="age[]">

input3

<input type="text" name="age[]">

input4

<input type="text" name="age[]">

input5

<input type="text" name="age[]">

<input type="submit" value="submit">

PHP脚本


<?php

$statement = $pdo->prepare("insert into AGEGroup (AGE) values ('$_POST['age']')");

            $statement->execute();

            echo "Added Successfully.";

?>

它只是添加了一条记录。怎么办5条记录都可以插入数据库???


非常感谢


或者使用for循环???


<?php

for($i=0, i<$_Post['age'][i],i++){

$statement = $pdo->prepare("insert into AGEGroup (AGE) values ('$_POST['age'][i]')");

            $statement->execute();

}

            echo "Added Successfully.";


?>


慕哥9229398
浏览 135回答 2
2回答

ibeautiful

由于所有 [x] 插入的查询保持相同,因此您应该在循环外进行准备,因此只完成一次(节省了不必要的服务器往返)您的准备还应该使用参数而不是将值直接连接到查询中,以避免SQL 注入攻击$stmt = $pdo->prepare("insert into AGEGroup (AGE) values (:age)");foreach ($_POST['age'] as $age) {    $stmt->execute([':age'=>$age]);}

函数式编程

虽然有可能在 for 循环的每次迭代中打开连接并不是最好的选择。我将连接整个字符串并仅发送一次查询。$query = "";&nbsp; &nbsp; for($i = 0, $i < $_Post['age'][$i], $i++{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $query .= "INSERT INTO AGEGroup (AGE) VALUES ('{$_POST['age'][$i]}');"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;$statement = $pdo->prepare($query);&nbsp;$statement->execute();注意变量名前的 $ 符号,在 PHP 中它为解释器标记即将到来的变量。
打开App,查看更多内容
随时随地看视频慕课网APP