for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql = "INSERT INTO `tblchitiethoadon`(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`)";
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
$result = mysql_query($sql);
/* $mahd i got it before */
}
}
I got 3 elements in array $cart,2 of them got cart[$i]['taken'] > 0
(i also echo $cart with $cart[$i]['taken'] > 0
condition for sure ) but in the database i just got the first and only one element.
Typo/Syntax Error
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
----------------------------------------------------------------------------------------------------------^(semicolon missing)
correct:
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price});";
-----------------------------------------------------------------------------------------------------------^
Reason:
Since you are using for loop to form the query.your query will look like
insert into table1(a,b,c) values(1,1,1)insert into table1(a,b,c) values(2,3,4) which is wrong syntactically.
you can echo your $sql and run it in phpmyadmin
Better Approach:
The better approach to your code(it will reduce the unwanted overhead,form the string inside the loop and execute it outside the loop):
$sql1 = "INSERT INTO `tblchitiethoadon`
(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`) VALUES";
for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql11.=" ({$mahd},{$proid},'{$prodName}',{$taken},{$price}),";
}
}
$sql=$sql1.$sql11;
$sql=trim($sql,",");//to remove the extra semicolon at the end of the string.
$result = mysql_query($sql);
Please Dont use mysql_* as these are depracated and you are prone to sql injections.
Try these this coding:
$sql = "INSERT INTO tblchitiethoadon (Ma_HD, Ma_SP, Ten_SP, SoLuong, Gia) VALUES ('$mahd','$proid','$prodName','$taken','$price')";
$result = mysql_query($sql);
Loop will execute count($cart) times and the insertion action will occure if ($cart[$i]['taken'] > 0)
is true.Make sure the condition is true for each time.