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++;
        }
3

2 Answers 2

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')
Sign up to request clarification or add additional context in comments.

1 Comment

@Uchiha pretty, but you do the count($products) in loop, should save it before looping ;p
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) 

3 Comments

don't forget to secure your data ^^
Thank u so much , i get the idea how to do so ,,, Thanks once again
@Bob0t yup dear , i will secure it but i was confused for such idea,, now it solved :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.