This question is an exact duplicate of:
Convert to "foreach loop" from "for loop" where using array and counting array positon with $serviceTitle after data will insert into MySQl
for($i=0;$i<count($serviceTitle);$i++){
$statement = $db->prepare("INSERT INTO invoice (orderNo,customerNo,productName,
price,quantity,amount,createDate,createTime,
createBy) VALUES (?,?,?,?,?,?,?,?,?)");
$statement->execute(array($orderNo,$customerNo,$serviceTitle[$i],$price[$i],$quantity[$i],$amount[$i],$date,$time,$createBy));
}
Before answer the question check this question : Insert Array values insert to single ID into mysql database using php and PDO
Thanks in Advance
</div>
Here's the code using foreach loop on $serviceTitle
$statement = $db->prepare("INSERT INTO invoice (orderNo,customerNo,productName,price,quantity,amount,createDate,createTime,createBy) VALUES (?,?,?,?,?,?,?,?,?)");
foreach ($serviceTitle as $key => $value) {
$statement->execute(array($orderNo,$customerNo,$value,$price[$key],$quantity[$key],$amount[$key],$date,$time,$createBy));
}
However it is better to use bulk insert rather than inserting each row individually.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ) {
date_default_timezone_set('Asia/Dacca');
/* check that all variables exist in the POST array */
if( isset( $_POST['Submit'], $_POST['serviceTitle'], $_POST['price'], $_POST['quantity'], $_POST['amount'], $_POST['orderNo'], $_POST['customerNo'] ) ){
/*
Assuming that the fields serviceTitle,price,quantity and amount
are named like field[] in the form then their values will be
arrays in the POST array
*/
$serviceTitle = $_POST['serviceTitle'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$amount = $_POST['amount'];
$orderNo = $_POST['orderNo'];
$customerNo = $_POST['customerNo'];
$date = date('Y-m-d');
$time = date('h:i:s');
$createBy = $_SESSION['sess_username'];
/* check that key variables are arrays as you intend to access as arrays below */
if( is_array( $serviceTitle ) && is_array( $price ) && is_array( $quantity ) && is_array( $amount ) ){
/* prepare the sql statement */
$sql='insert into `invoice` ( `orderno`, `customerno`, `productname`, `price`, `quantity`, `amount`, `createdate`, `createtime`, `createby` ) values (?,?,?,?,?,?,?,?,?)';
$stmt=$db->prepare( $sql );
if( $stmt ){
foreach( $serviceTitle as $i => $arr ){
try{
$args=array(
$orderNo,
$customerNo,
$arr[$i],
$price[$i],
$quantity[$i],
$amount[$i],
$date,
$time,
$createBy
);
$stmt->execute( $args );
}catch( PDOException $e ){
echo $e->getMessage();
}
}
$stmt->close();
$db->close();
$_SESSION['orderNo'] = $_POST['orderNo'];
$_SESSION['customerNo'] = $_POST['customerNo'];
ob_clean();
header( "location: order_confirm_tech_step2.php" );
} else {
echo "error preparing sql"
}
} else {
echo "error, one or more variables are not arrays"
}
} else {
echo "error, one or more variables are not available"
}
}
?>