简体   繁体   中英

Can't get selected value from dropdown in PHP, SQL

I have the following code:

<form action="MovieDatabase.php" method='post'>
  <select name="director_movie">
    <?php 

        $sql = mysqli_query($mysql, "SELECT DISTINCT Title FROM Film2");

        while ($row = $sql->fetch_assoc()){

    ?>
    <option value="director_movie1" id="film_id"><?php echo $row['Title']; ?></option>

    <?php
    // close while loop 
    }
    ?>
</form>

For the drop-down, which uses the values from SQL table. So the drop-down has values as movie titles.

When I try to access the selected value from MovieDatabase.php like that:

$_POST['director_movie'];  

and when I try to echo it, it only shows me option value direcotr_movie1 which is not what I'm looking for. In this case I want to get the title of the movie, which was selected from the dropdown.

What am I doing wrong?

You hard-coded same value for each option in your code in this line:-

<option value="director_movie1" id="film_id"><?php echo $row['Title']; ?></option>

That's why you are getting same-value every time .

Change it to below:-

<option value="<?php echo $row['Title'];?>"><?php echo $row['Title'];?></option>

Now it will work fine.

Note:- id need to be unique for each HTML element so remove that repetitive id (i don't think you have any need of that)

Change this

<option value="director_movie1" id="film_id"><?php echo $row['Title']; ?></option>

to

<option value=<?php echo $row['Title']; ?> id="film_id"><?php echo $row['Title']; ?></option>

you are hardcoding your value <option value="director_movie1" id="film_id"> and wondering why your form submits your hardcoded value?

The movie title that is shown in your select is just what the users can see. your form submits what you put into value=<your required information here>

On another note: Using the title as the field might result in problems when using anything but chars / numbers as the title when you want to fetch the movie information based on the selected title. Better use the ID of your movie

1st : Change your value attribute to value="<?php echo $row['Title']; ?>"

2nd : Id attribute is unique for each element. remove it from option tag id="film_id"

 <option value="<?php echo $row['Title']; ?>" ><?php echo $row['Title']; ?></option>

change below line

<option value="director_movie1" id="film_id"><?php echo $row['Title']; ?></option>

with

<option value="<?php echo $row['Title']; ?>" ><?php echo $row['Title']; ?></option>

Now you will get dynamic value different options also id can not have same value for all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM