Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables from one table to another in another PHP page [duplicate]

Tags:

html

php

mysql

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:

The product table

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:

The selected products

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?

like image 855
tsvenbla Avatar asked Nov 28 '16 09:11

tsvenbla


1 Answers

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.

like image 185
Christoph Diegelmann Avatar answered Sep 28 '22 19:09

Christoph Diegelmann