John
John

Reputation: 1594

Retrieve post value from php of dropdown select upon page

I have a drop down select inside of a form on my page nice.php which is submitted using a button

<form action="nice.php" method="post">
<select name="CarList">
<option value="0"> - Select Car - </option>
<option value="AM">Aston Martin</option>
<option value="KG">Koenigsegg</option>
<option value="MB">Mercedes Benz</option>
</select>

<input type="submit">
</form>

After making a selection is it possible to submit the form, reload the same page however with the value from the dropdown into a php variable $SelectedCar?

Upvotes: 0

Views: 1761

Answers (2)

Jacques Koekemoer
Jacques Koekemoer

Reputation: 1414

Add the code to the top of your php page and remove the form tags. This should do a post back to the same page. (Remember to check if any variables are set in $_POST )

I haven't tested this suggestion yet but it should work

** Edit.

So Your HTML should look something like this:

    <?php 
    if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
        $CarListValue = $_POST['CarList'];

        if($CarListValue != 0){ // a selection has been made using car list
            $SelectedCar = $CarListValue
            echo $SelectedCar  // should print either 'AM', 'KG', or 'MB'
        }
        else{
            echo '<p>No Selection has been made and submitted yet</p>';
        }
    }

    ?>

    <html>
    <head>
    <title>Nice.php</title>
    </head>
    <body>
        <select name="CarList">
        <option value="0"> - Select Car - </option>
        <option value="AM">Aston Martin</option>
        <option value="KG">Koenigsegg</option>
        <option value="MB">Mercedes Benz</option>
        </select>

        <submit>Submit Form</submit>
    </body>
    </html>

You could then take your validation to another level and change the php code like this as well:

    <?php 

    $ValidCars = array('AM','KG','MB');

    if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
        $CarListValue = $_POST['CarList'];

        if(in_array($CarListValue,strtoupper($ValidCars),false) !== true){
            die('<b>The car selection you made is invalid</b>');
        }

        if($CarListValue != 0){ // a selection has been made using car list
            $SelectedCar = $CarListValue
            echo $SelectedCar  // should print either 'AM', 'KG', or 'MB'
        }
        else{
            echo '<p>No Selection has been made and submitted yet</p>';
        }
    }

    ?>

I just want to say again that this code is untested but the in theory the code should work without any error

Upvotes: 0

pythonjsgeo
pythonjsgeo

Reputation: 5411

if(!empty($_POST['CarList'])){
    $SelectedCar = $_POST['CarList'];
    echo $SelectedCar;
}else{
    echo '<p>No Selection has been made and submitted yet</p>';
}

Upvotes: 1

Related Questions