Question about adding a product to cart


I’m practising PHP, building a simple webshop.

Now, I have come into this dilemma which to use.

'<form action="" method="POST">	  
<tr> <th>Product:</th> <td>'.$product['item'].'</td> </tr>
<tr> <th>Price:</th> <td>'.$product['price'].'</td> </tr>
<tr> <th>How many?:</th> <td><input type="text" name="quantity" /></td> <td>'.$product['unit'].'</td> </tr>
<a href="shop.php?cart=add&amp;product='.$product['item'].'&amp;quantity='.$_POST['quantity'].'">Add to cart</a>

What I’m trying to do now is, add the POST[‘quantity’] to the URL, which doesn’t work, I guess it wants a submit.
If I use POST’s submit as add to cart, then I’d have to use for loop for adding different names to different FORM’s, else it would be one big form.
Also, I’ve seen people add echo to every line, what’s with that?
What are your suggestions, how to do this?
How to improve that code?

It shouldn’t be difficult. The only way to get any information from a user is via the query string. This can be POST or GET, the main difference is semantic.

The problem you have above is that you are trying to build a link based on information you don’t have: the quantity. They must “submit” this info to the server or you won’t know it.

Ignoring JS, you could use a bunch of links with varying quantities, or you could use the form you have with a couple of minor modifications. Just use a hidden input type to pass on the product id and all should be fine :slight_smile:

Re the echo question, I would suggest this as the best way to do things (given the large amount of html vs php in your code):

<form action="" method="POST">      
<tr> <th>Product:</th> <td><?php echo $product['item'] ?></td> </tr>
<tr> <th>Price:</th> <td><?php echo $product['price'] ?></td> </tr>
<tr> <th>How many?:</th> <td><input type="text" name="quantity" /></td> <td><?php echo $product['unit'] ?></td> </tr>
/ ...

Well, if you ask me a form without a submit seems pretty useless.

If you want GET variables (i.e. in the URL) simple links would do.

If you want the form to do both POST and GET, I haven’t tried it, but I think if you did the GETs in the form’s action it just might work.

POST variables are not on the URL. GET variables go on the URL.

You’re also thinking in two scopes here - client side and server side.

Change your link to a submit.

what troubles me is that I don’t know how should I get the Input from the user and put it in the url, can’t do that without submit. I guess by using forms, the add to cart would need to go rather difficult.