所以我一直在寻找过去3天的指示,以确定是否可以这样做。我想创建一个注册页面,用户选择家庭成员的数量,然后将显示该表格的数量供用户填写。这可以是1到10之间的任何地方。这部分已经完成,我可以在打印数组时得到以下结果。我的问题是,我现在可以把这些信息放在一个带有每个人记录的mysql数据库中吗?
我使用此代码获取以下数组:
foreach($_POST as $key=>$value)
{
echo "$key=$value"."<br>";
}
// $ key = $ value
的结果firstname0=John
lastname0=smith
years0=2011
street_address0=18 Kelly Lane
city0=test town
phone0=000 000 0000
email0=test@gmail.com
registration=15.00
pub=15.00
golf=90.00
basketball=NaN
run=10.00
hockey=10.00
banquet=25.00
ecumenical_service=1
T_shirt=20.00
Golf_shirt=
Mug=
Drinking_glass=
DVD=
Hats=
firstname1=John
lastname1=Smith2
graduated1=2014
registration1=15.00
T_shirt1=40.00
Golf_shirt1=
Mug1=
Drinking_glass1=
DVD1=
Hats1=
firstname2=Jane
lastname2=Smith3
graduated2=1990
registration2=15.00
show2=15.00
T_shirt2=
Golf_shirt2=
Mug2=
Drinking_glass2=
DVD2=
Hats2=
firstname3=Jane
lastname3=Smith Jr.
graduated3=2000
registration3=15.00
pub3=15.00
T_shirt3=
Golf_shirt3=
Mug3=
Drinking_glass3=
DVD3=
Hats3=
你可以看到每个字段名都有编号,firstname1,firstname2等等......所以我的问题是我可以把这个数组插入到数据库中,还是我最初想的如何创建多个动态表单有缺陷?
答案 0 :(得分:0)
在表单中使用<input type="text" name="firstname[]" />
$firstname = $_POST['firstname'];
$stmt = $pdo->prepare('INSERT INTO persons VALUES(:firstname)');
foreach($registers as $key => $register){
$stmt->bindValue(':firstname', $firstname[$key]);
$stmt->execute();
}
答案 1 :(得分:0)
好的,这是一个可行的解决方案,我只是为你测试它并且它有效。
这里的完整示例仅用于演示目的,因此您了解解决它的概念。
欢迎您更改或修改它以完全符合您的要求。
我用mysqli语句和一个虚拟数据库customer_info表做了这个例子。你需要更改名称,创建数据库等。
我只选择了3个字段来测试它,但它可以扩展为无限字段/键。
有趣的是,我用户<?php
$data = [
"firstname0" => "John1",
"lastname0" => "Smith1",
"years0" => "2011",
"firstname1" => "John2",
"lastname1" => "Smith2",
"years1" => "2012",
"firstname2" => "John3",
"lastname2" => "Smith3",
"years3" => "2013",
"firstname4" => "John4",
"lastname4" => "Smith4",
"years4" => "2014",
];
// this is an example of database I build modified to full fit your needs
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dummy";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
//change 3 to 21 or the total fields
$max_fields = 3;
$value = array_values($data);
for ($i = 0; $i < count($value); $i = $i + $max_fields)
{
$value1 = $value[$i + 0];
$value2 = $value[$i + 1];
$value3 = $value[$i + 2];
//add the number of fields here up to 20, that gives totally 21 fields including 0. value1 is firstname, value2 is lastname etc.
//$value4 = $value[$i + 3];
// this is an example of database I build modified to regarding to your database table design
mysqli_query($conn, "INSERT INTO customer_info
(firstname, lastname, years)
VALUES
(' $value1 ', ' $value2 ', ' $value3 ')");
echo "data is inserted in your database";
}
mysqli_close($conn);
?>
将您的所有按键名称转换为数字。以这种方式工作更容易。
您需要将数据作为数组传递,如示例所示。
for循环正在递增,具体取决于总字段/键。
以下是解决方案:
"localhost/foo/bar/"
祝你好运