-1

I created some PHP code to get values from a database and show them as an option in a form I created using HTML. Now I want to be able to select one of those options and then process that in POST. But it gives me an error that my index is undefined when I try to get that value in POST. So I guess my question is, is getting this value possible? If so, how would I accomplish this?

Here is my code:

<form method="post" action="dayzconfigedit.php">
<select name="item1">;
    <?php
        //Display the Items from the database in a dropdown menu
        $sql = "SELECT item_id FROM `all_items`";
        $result = $conn->query($sql);
        for($x = 0; $x < $result->num_rows; $x++) {
            $row = $result->fetch_assoc();
            echo "<option value=\"{$row["item_id"]}\">{$row["item_id"]}</option>";
        }
    ?>
</select>
</form>

Then I try to get value in POST:

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    //Grab Selected Items from Form
    $item1 = "$_POST[item1]";
}

Thanks in advance!

I skimmed through the post that supposedly answers my question but I still can't solve this issue because I don't know why the index is undefined in the POST array.

Gavin
  • 3
  • 3

3 Answers3

1

You need to grab item 1 like this;

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    //Grab Selected Items from Form
    $item1 = ! empty($_POST['item1']) ? $_POST['item1'] : null;
}

Also, please update where you echo the option to be;

echo"<option value=\"{$row["item_id"]}\">{$row["item_id"]}</option>";
Simon R
  • 3,732
  • 4
  • 31
  • 39
0

You may either missed to specify method="post" in form tag .. or you missed to specify the name of the field <select> tag like <select name="item1">.

Now you can access the submitted value in $_POST["item1"]

Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45
0

I am not well versed in PHP but i think your code should read

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    //Grab Selected Items from Form
    $item1 = $_POST["item1"]; //Take note of this line
}