PHP:从下拉列表中回显选定的值

时间:2017-03-29 15:05:14

标签: php html sql

我有一个我使用MySQL表创建的下拉列表。下拉列表工作正常,但由于某种原因,我无法回显所选的值,这是我的代码:

<?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>

这是我尝试过的:

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

2 个答案:

答案 0 :(得分:0)

下拉列表必须包含在表单中。如果未设置提交表单,则无法从$_POST数组中获取值。
您应该使用以下代码:

$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'];
}

我希望这会对你有所帮助!

答案 1 :(得分:0)

试试这种方式

RepositoryItemWriter