因此,过去 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 等等...所以我的问题是我可以把这个数组插入到数据库中还是我最初关于如何创建多个动态表单的想法有缺陷?
最佳答案
好的,这是一个可行的解决方案,我刚刚为您测试了它并且有效。
此处的完整示例用于演示目的,以便您了解解决它的概念。
欢迎您更改或修改它以完全满足您的要求。
我用 mysqli 语句和一个虚拟数据库 customer_info 表做了这个例子。这取决于您更改名称、创建数据库等。
我只选择了 3 个字段来测试它,但它可以扩展到无限的字段/键。
让您知道的有趣的是我使用 array_values($data);
这会将您所有的键名转换为数字。使以这种方式工作更容易。
您需要将数据作为示例中所示的数组传递。
for 循环根据总字段/键递增。
解决方法如下:
<?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);
?>
祝你好运
关于php - 发送多个相同的表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31880137/