0

I'm getting array value from cart table and I want to insert cart array value into my order table but the problem I was facing is only last array value only inserting into my database but I want to insert all cart value into my order table.

/*This is the form page I was getting cart value*/
<form>
<input type="text" name="cid[]" value="1">
<input type="text" name="pid[]" value="2">
<input type="text" name="quantity[]" value="3">
<input type="text" name="total[]" value="5">
</form>

/*Once the form is submited the action comes to this php page*/

<?php 
$cid = $_POST['cid'];
$pid = $_POST['pid'];
$quantity = $_POST['quantity'];
$total = $_POST['cid'];

$insertquery = "INSERT INTO orders(cid,pid,quantity,total) VALUES('$cid','$pid','$quantity','$total')";

?>


/*After excution of this code only inseting the last value, not inserting the all value */

3

1 Answer 1

1

Since your form elements are arrays [], loop over them like this:

$rowCount = count($_POST['cid']);

for($=0; $i < $rowCount; $i++) {

    $cid = $_POST['cid'][$i];
    $pid = $_POST['pid'][$i];
    $quantity = $_POST['quantity'][$i];
    $total = $_POST['total'][$i];

    // ...

}
Sign up to request clarification or add additional context in comments.

3 Comments

Your script is wide open to SQL Injection Attack Even if you are escaping inputs, its not safe! Use prepared parameterized statements in either the MYSQLI_ or PDO API's
And it would run faster using a Prepare Once and execute Many method
@RiggsFolly thx for reminding me to always point out injection problems if i copy/paste non-safe code from a beginner. Changed it.. IMO talking about prepare/execute in your follow up comment is off topic. Correct me if i am wrong :)

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.