Anthony
Anthony

Reputation: 1

php multiple dropdown menu with same name can't get the value

okay, im new in this site also new in php and can't get the logic on this,

i have a product page that shows the name, quantity and an add to cart button in each row of product

i made this just cutted of some code

    while($showProducts = mysql_fetch_array($products))
            {
            $currenQuantity = $showProducts['current_quantity'];
            $prodid = $showProducts['product_id'];
    echo"<select name='quan'>";

                for ($x=0;$x<=$currenQuantity;$x++)
            {
                if($currenQuantity != 0)
                {
                echo "<option value=$x> $x </option>";
                }
            }
     echo"</select><br/>";
     }

now the problem is every time i tried to get the value by using $_POST['quan'] the value that i always get is the default value 1 even i select a different value of quantity of a certain product, and i'm blanked with ideas.

Upvotes: 0

Views: 1737

Answers (3)

Adam Chysky
Adam Chysky

Reputation: 386

If you have more selectboxes with the same name (quan) in one form, you are getting value of the last one.

You should change the selectbox definition to:

echo"<select name='quan[" . $prodid . "]'>";

then you can access the values using:

$_POST["quan"][$some_product_id]
$_POST["quan"][$another_product_id]

Upvotes: 0

Michael Walter
Michael Walter

Reputation: 1477

You can't use the same name for an input/select field in a form. You have to specify a diffrent name or create an indexed array:

<select name="quan[$prodid]">

You can acces it via

$_POST['quan'][$prodid]

Upvotes: 2

mgrueter
mgrueter

Reputation: 1420

Just a wild guess: has each of your product rows a select named 'quan'? Then you're getting the last select named 'quan' in your POST data.

Prefix each of the quantities selects with name of the product, or some kind of a (scrambled) id.

Additionally: If you don't want to have a 0 in your select, don't start the for loop with 0

for ($x=1;$x<=$currenQuantity;$x++)

if the current quantity is 0, the for loop doesn't get executed.

Upvotes: 0

Related Questions