Question

Kinda strange... I'm building a shopping cart. When the user types the quantity he wants and hits "add to cart", the <form> action should redirect them with a PHP $_SERVER['QUERY_STRING'] AND some other information (i.e. the product id, fetched in MySQL).

Here's my form, all in a PHP echo...

<?php
echo '<form method="GET" action="cart.php?'.$_SERVER['QUERY_STRING'].'&action=add&item_id='.$data->item_id.'">
<small>Quantity </small><input type="text" size="2" placeholder="1" name="add_quantity">
<input type="submit" name="add_clicked" class="button" value="Add to Cart">
</form>';
?>

Upon submission, the URL redirects to cart.php but only includes the query string, but leaves out the item id and the action=add.

Supposing I typed '2' in the quantity box, the URL looks like this cart.php?add_quantity=2 and nothing after that.

Would appreciate help! Thanks!

Was it helpful?

Solution 2

Submitting a form with GET will overwrite any query string you'd put in the url (I'm not sure what you wanted to do with your $_SERVER['QUERY_STRING'] though as that would give the query string used to access the page where your form is.

What you'll want to do is to use hidden input fields in your form for your action and item_id attributes.

<form method="GET" action="cart.php">
<input type="hidden" name="action" value="add"/>
<input type="hidden" name="item_id" value="<?=$data->item_id?>"/>
<small>Quantity </small><input type="text" size="2" placeholder="1" name="add_quantity">
<input type="submit" name="add_clicked" class="button" value="Add to Cart">
</form>

Upon submission this will go to the url cart.php?action=add&item_id=1234&add_quantity=2

Alternatively you could (and most likely should) submit the form via POST; then any data in the form will be sent as POST parameters and the query string parameters defined in your action will be kept.

OTHER TIPS

When you submit a form via GET, the form data submission process will overwrite any existing query string that might be set in the address you put into the action attribute.

Use hidden form fields instead to transport your additional values.

(And as @Simon already said in his comment, go read up on what you have to do to prevent XSS when outputting data that was send from the client before.)

Pass the info in the query strings via a hidden field. So let's assume you're passing the account number in the query string, it would look like this:

<input type="hidden" name="account_number" value="$account_number">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top