I'm doing an assignment in school where we should simulate a web retail store that sends products from a database via PHP to the end user. The user should then be able to add the products to the cart by a checkbox and press a button that takes them to the cart, where only the selected items from the product table should show.
I've made some great progress, but I'm stuck on this teeny tiny problem, which is: I can't figure out how to present the selected items in a table. Let me show you how my product table looks like right now:
And the code:
<form action="selected_products.php" method="POST">
<table>
<tr>
<th>Select</th>
<th>Product-ID</th>
<th>Product Name</th>
<th>Price SEK</th>
<tr>
<?php
// Print out all entries in a table
foreach ($rows as $value) {
extract($value);
echo "<tr><td><input type='checkbox' name='SelectedData[]' alt='Checkbox' value='$id&$name&$price'></td>";
echo "</td><td>".$id.'';
echo "</td><td>".$name.'';
echo "</td><td>".$price.'';
echo "</td></tr>";
}
?>
</table>
<br>
<input type="submit" value="Add to cart" />
</form>
When the user selects the products with the checkbox and presses the button, it takes them to the selected_products.php
page, which would look like this:
And the code:
<table>
<tr>
<th>Product-ID</th>
<th>Product Name</th>
<th>Price SEK</th>
<tr>
<?php
if(!empty($_POST['SelectedData'])) {
foreach($_POST['SelectedData'] as $selected) {
echo "<tr><td>".$selected.'';
echo "</td></tr>";
}
}
?>
So, my question is: how can I make the selected products fill out the entire table, instead of being mushed up in one column like they are now? I do pass it with value='$id&$name&$price'
, but how can I make this value string to put every entry in its corresponding column on the selected_products.php
page?
As already answered in the comments you could use explode()
to solve this problem.
foreach($_POST['SelectedData'] as $selected) {
list($id, $name, $price) = explode("&", $selected);
echo "<tr><td>".$id.'';
echo "</td><td>".$name.'';
echo "</td><td>".$price.'';
echo "</td></tr>";
}
but this is a rather bad idea because it allows everybody to fill it with whatever they want. This is because everybody can send a post request with any content they want. A better way would be to set selected to the id of the item and then read the data you need from the database again using the id of the item. This way only items that are in the database can be displayed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With