Solution:
title: "Insert multiple rows into MySQL with PHP using foreach arrays"
tags: php, mysql
canonical_url: https://kodlogs.com/blog/448/insert-multiple-rows-into-mysql-with-php-using-foreach-arrays
Code: foreach array
$row_data = array();
foreach($_POST['name'] as $row=>$Name) {
$issuedate=('Y-m-d');
$issuetime=('h:i:s');
$name=mysql_real_escape_string($Name);
$id=mysql_real_escape_string($_POST['id'][$row]);
$icno=mysql_real_escape_string($_POST['icno'][$row]);
$route=mysql_real_escape_string($_POST['route'][$row]);
$price=mysql_real_escape_string($_POST['price'][$row]);
$date=mysql_real_escape_string($_POST['date'][$row]);
$time=mysql_real_escape_string($_POST['time'][$row]);
$username=mysql_real_escape_string($_POST['username'][$row]);
$pax=mysql_real_escape_string($_POST['pax'][$row]);
$paxcur = $pax - $row;
$row_data[] = "(',', '$name', '$icno', '$route', '$price', '$date', '$time', '$username', '$issuedate', '$issuetime')";
}
if (!empty($row_data)) {
$query = 'INSERT INTO issue(id, name, icno, route, price, date, time, username, issuedate, issuetime) VALUES '.implode(',', $row_data);
if (mysql_query($query))
echo 'Successful inserts: ' . mysql_affected_rows();
else
echo 'query failed';
}
The Complete Code
foreach ($service as $value) {
$stmt = $connection->prepare('INSERT into services_list (servicename) values (?)');
$stmt->bind_param('s',$value);
$stmt->execute();
$stmt->close();
}
}
foreach ($service as $value) {
$stmt = $connection->prepare('INSERT into services_list (servicename) values (?)');
$stmt->bind_param('s',$value);
$stmt->execute();
$stmt->close();
foreach ($price as $euro){
$stmt = $connection->prepare('INSERT into services_list (price) values (?)');
$stmt->bind_param('s',$euro);
$stmt->execute();
$stmt->close();
}
}
Top comments (0)