简体   繁体   中英

PHP: echo selected value from a drop down list

I have this drop-down list that I created using one of MySQL table. The drop-down list is working fine but for some reason I am not able to echo the selected value here is my code:

<?php
      require_once('config.php');
      // CONNECT
       mysql_connect('localhost', 'root', 'password');
       mysql_select_db('Database');

 ?>
 // other.php is another php file
 <form action="other.php" method="POST">

            <label>Quantity:</label>
            <input type="number" min="1" name="quantity" value="1"/>
            <br/>
            <hr/>

            <?php
                    echo makeFormEntry('Product Type', 'type', $types);
                    echo makeFormEntry('Product Occasion', 'occasion', $occasions);
                    echo makeFormEntry('Product Size', 'size', $sizes);
            $sql = "SELECT * FROM Table";
            $result = mysql_query($sql);
            echo "<b>Name : </b>" . "<select id='Name' name='Name'>";
            while ($row = mysql_fetch_array($result)) {
             echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "</option>";
            }
                    echo "</select><br>";
               echo "<input type='submit'/><input type='reset'/>";
  ?>
  </form>

here is what I have tried:

  $n=$_POST['Name'];
   echo $n;

The drop down list must be contained in a form. You can't get a value from the $_POST array if it isn't set submitting a form.
You should use this code :

$sql = "SELECT * FROM TABLE";
$result = mysql_query($sql);
echo "Options" . "<form method='post'><select id='name' name='name'>";
while ($row = mysql_fetch_array($result)) {
     echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "
     </option>";
}
echo "</select><input type='submit' name='submit'></form><br>";

if(isset($_POST['submit'])) {
    echo $_POST['name'];
}

I hope this is going to help you!

试试这个

  echo "<option if($row["Name"]=="Doe") ? "selected='selected'":"" value='".$row['Name']."'>".$row["Name"]."</option>";

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