1

Please somebody help me. In below code the query will execute 3 times , means query execution will depend on number of elements in array. Please guide me how to run this query with inserting all data at once

 $products = array("shirt" , "paint" , "socks");
    $price = array("200" , "600" , "50");
    $quantity = array("3" , "2" , "2");

        $num = 0; while($num <= count($products))
        {
            $mysqli->query("insert into new_order set 
                            product = '".$products[$num]."' ,
                            price = '".$price[$num]."' , 
                            quantity = '".$quantity[$num]."'
                          ");

                          $num++;
        }
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
Aftab Ahmad
  • 354
  • 1
  • 2
  • 16

2 Answers2

2

Iterate over each item in $products to build $sql string:

$sql = "insert into new_order(product, price, quantity) values ";
for($i=0;$i<count($products);$i++){
    $sql .= "({$products[$i]}, {$price[$i]}, {$quantity[$i]}),";
}
$sql = substr($sql,0,-1); //cut off the trailing comma
$mysqli->query($sql);

// insert into new_order(product, price, quantity) values (shirt, 200, 3),(paint, 600, 2),(socks, 50, 2) 
n-dru
  • 9,285
  • 2
  • 29
  • 42
2

It won't throw any error untill you'll be getting same number of values within an array

$counts = count($products);
$query = "insert into new_order (product,price,quantity) values ";
foreach($products as $key => $value){
    $query .= "('$value','$price[$key]','$quantity[$key]')";
    $query .= (++$key == $counts) ? '' : ',';
}
$mysqli->query($query);

Query looks like:

//insert into new_order (product,price,quantity) values('shirt','200','3'),('paint','600','2'),('socks','50','2')
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
  • @Uchiha pretty, but you do the `count($products)` in loop, should save it before looping ;p – Bobot May 16 '15 at 14:00