heisenberg
heisenberg

Reputation: 1954

Passing a multidimensional array through hidden input via POST

So I researched online to see how I can pass an array which I POST through form.

Here's what I did.

    $itemsArr = array();
    while ($row = $result->fetch_assoc()) {
    $totalPrice += $row['item_price'];
    $totalItemsOnCart += $row['quantity'];
    $itemId = $row['item_idPK'];
    $itemName = $row['item_name'];
    $itemPrice = $row['item_price'];
    $itemQty = $row['quantity'];
    $itemsArr[] = array($userId, $itemId, $itemQty);

    echo "<tr>";
    echo "<td>".$itemId."</td>";
    echo "<td>".$itemName."</td>";
    echo "<td>".$itemPrice."</td>";
    echo "<td>".$itemQty."</td>";
    echo "</tr>";   
    }

Then, I used the foreach loop to iterate through the multidimensional array.

echo "<form class = 'BreadCode' action='Function_Cart.php' method='POST'>";
foreach($itemsArr as $value){
    print_r($value);
    echo '<input type="hidden" name="itemsArr[]" value="'. $value. '">';
}
    echo "<input type='hidden' name='userId' value='$userId'>";
    echo "<input type='hidden' name='itemId' value='$itemId'>";
    echo "<input type='hidden' name='quantity' value='$itemQty'>";
    echo "<input class='PayButton' type='submit' name='Btn-pay' value='Pay'>";
    echo "</form>";

I keep getting an "Array to string conversion" error with or without the echo for the hidden input within the foreach() loop

I haven't really tried sending an array via form through POST method in the past. I just don't know how to go about this.

Below is the result of print_r()

Array ( [0] => 5112 [1] => 105 [2] => 2 ) 
Array ( [0] => 5112 [1] => 104 [2] => 1 )

Please help.

Thank you.

Upvotes: 2

Views: 2178

Answers (2)

Bhupendra Mistry
Bhupendra Mistry

Reputation: 628

You just need to encode array to json and decode it on action page

echo '<input type="hidden" name="itemsArr" value="'.json_encode($itemsArr). '">';

And at your action Page just decode it

$itemsArr = json_decode($_POST['itemsArr'],true)

Upvotes: 2

urfusion
urfusion

Reputation: 5501

There is no need for place foreach and increase execution time. You can simply do that by using json_encode.

echo "<form class = 'BreadCode' action='Function_Cart.php' method='POST'>";
echo '<input type="hidden" name="itemsArr" value="' . json_encode($itemsArr) . '">';

echo "<input type='hidden' name='userId' value='$userId'>";
echo "<input type='hidden' name='itemId' value='$itemId'>";
echo "<input type='hidden' name='quantity' value='$itemQty'>";
echo "<input class='PayButton' type='submit' name='Btn-pay' value='Pay'>";
echo "</form>";

Upvotes: 1

Related Questions