[英]PHP mysql insert associative array into database from a “dynamic” form
[英]Insert Data to mysql database from Associative array in PHP
我有以下关联数组
Array (
[0] => Array
(
[0] => Liane Lanford
[1] => Ken Christenson
[2] => Melissa Jaramillo
)
[1] => Array
(
[0] => $310.40
[1] => $134.75
[2] => $951.78
)
[2] => Array
(
[0] => $0.00
[1] => $0.00
[2] => $0.00
)
[3] => Array
(
[0] => $325.92
[1] => $141.49
[2] => $999.37
)
)
阵列中有 3 个客户。 数量可以是 4.5 或更多。 我想将数组中的数据插入到数据库中,如下表
我该如何编写 foreach 循环。 我尝试了以下但不起作用
foreach ($array as $payment_type => $payment) {
foreach ($array[payment_type] as $pay => $value) {
mysqli_query($link, "INSERT INTO table(name,subtotal,holdback,total) VALUES ('$pay[0]','$pay[1]','$pay[2]','$pay[3]') ");
}
}
您需要做的就是循环数组,然后使用索引访问所有其他值子数组值。 我还使用了正确的准备和绑定机制来避免SQL 注入
$stmt = $link->prepare("INSERT INTO table (name,subtotal,holdback,total) VALUES (?,?,?,?)");
foreach ($array[0] as $idx => $payment) {
$stmt->bind_param('sdsd', $payment,
$array[1][$idx],
$array[2][$idx],
$array[3][$idx]
);
$stmt->execute();
}
一些代码开始,使用准备好的语句来防止 SQL 注入:
$stmt = $link->prepare('INSERT INTO table(name,subtotal,holdback,total) VALUES (?, ?, ?, ?)');
foreach ($array[0] as $key => $value) {
$stmt->bind_param('ssss', $value, $array[1][$key], $array[2][$key], $array[3][$key]);
$stmt->execute();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.