I have the following Associative array
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
)
)
There are 3 customers in the array. The number may be 4,5 or more. I want to insert the data from the array to the database like following table
How can i write the foreach loop. I tried the following but not working
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]') ");
}
}
All you need to do is loop the array and then use the index to access all the other values sub array values. I also used the correct prepare and bind mechanism to avoid SQL Injection
$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();
}
Some code to start with, using prepared statements to prevent SQL-injections:
$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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.