I am learning PHP and trying to make a simple cart/processing script.
I have created the item cart fine, but I am having trouble displaying information in my receipt when a user commits to buying the item(s) in their cart.
To save space/time I have omitted my item lists and the generation of the cart, they can be found here if you need it.
Here is the PHP that posts the data to my checkout.php script cart.php (Updated to reflect change)
<?php
session_start(); ?>
<form name="cart" id="cart" action="checkout.php" target='_blank'
method='post'>
<h1>Your Cart:</h1>
<table>
<tr>
<td><span class='title'>ID</span></td>
<td><span class='title'>Product</span></td>
<td><span class='title'>Price</span></td>
</tr>
<?php
// Set a default total
$total = 0;
foreach ( $_SESSION['cart'] as $cartid ) {
?>
<tr>
<td width="20%">
<?php echo $cartid; ?> <input type="hidden" name="id[]"
value="<?php echo $cartid; ?>">
</td>
<td width="100%">
<?php echo $title?>
<input type="hidden" name="title[]" value="<?php echo $title; ?>">
</td>
<td width="100%">$<?php echo $price;?>
<input type="hidden" name="prices[]" value="<?php echo $price; ?>">
</td>
</tr>
<?php
$total += $price;
} // end foreach
?>
<tr>
<td>Total</td>
<td></td>
<td>$<?php echo $total; ?></td>
</tr>
</table>
<input type="submit" value="Buy" class="submit-button" />
</form>
checkout.php (Updated to reflect change)
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<?php
foreach($_POST['ids'] as $id) {
echo "
<tr>
<td>$id</td>
<td>$_POST['titles'][$id]</td>
<td>$_POST['prices'][$id]</td>
</tr>
";
}
?>
<tr>
<td>Total</td>
<td></td>
<td>$</td>
</tr>
</table>
I cannot seem to get the foreach loop to read the item id, title, or price. I can see the array is being passed using print_r($_POST); but it is indexing each item as a new array item e.g:
Array
(
[checkout] => Array
(
[0] => A123
[1] => Item1
[2] => 1000
[3] => Z999
[4] => Item999
[5] => 9999
)
)
How can I post the information in a more meaningful way i.e. associated array. Then use that associated array to display information in a table like format?
Expected output
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>A123</td>
<td>Item1</td>
<td>$1000</td>
</tr>
<tr>
<td>Z999</td>
<td>Item999</td>
<td>$9999</td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td>$10999</td>
</tr>
</table>
N.B: This is just a learning exercise so array sanitizing not required, and no SQL.
Edit: Updated to reflect @Obsidian Age recommendations, getting parse error now