使用PHP动态显示选项值

时间:2014-11-26 02:26:06

标签: php html mysql forms dynamic

我是PHP的新手,并创建了一个非常基本的HTML表单。正如您在我的表单中看到的那样,选项值都是手工完成的(还有更多,我只是简化了这个例子)。我想要的是只使用PHP动态生成这些内容,这样我就可以每年添加一次等等。

我已经做了一些搜索,但我似乎无法找到我想要的东西,所以我想在这里问。从我收集到的东西,我需要创建一个查询并以某种方式回显选项值,虽然我不知道如何做到这一点。

SELECT gameYear from games

我猜上面的内容是正确的查询,因为表格中需要的是bookYear吗?

<form id = "gameYear" method="get" action="result.php">
<label> 
    Game Year
    <select name="gameYear">
       <option value="2000">2000</option>
       <option value="2001">2001</option>
       <option value="2002">2002</option>
    </select>
</label>
   <input type = "submit" name="search" value = "Search">
</form>

谢谢,感谢任何帮助/指导。

2 个答案:

答案 0 :(得分:2)

<form id = "gameYear" method="get" action="result.php">
<label> 
Game Year
<select name="gameYear">
<option value=''>--Select Year--</option>
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$SqlResult = mysqli_query($link, "SELECT gameYear from games");
while($Row = mysqli_fetch_array($SqlResult))
{
  ?>
  <option value="<?php echo $Row['gameYear'] ?>"><?php echo $Row['gameYear'] ?></option>
}
?>
</select>
</label>
<input type = "submit" name="search" value = "Search">
</form>

答案 1 :(得分:1)

<?php $sql = "SELECT gameYear from games order by gameYear ASC";
    $result = mysql_query($sql, $connection) or die ("Couldn't perform query $sql <br />".mysql_error()); ?>


<form id="gameYear" method="get" action="result.php">
<label>Game Year
<select name="gameYear">
<?php while($row = mysql_fetch_array($result)){ ?>                        
<option value="<?php echo $row['gameYear'] ?>"><?php echo $row['gameYear']?></option>
<?php } ?>
</select>
</label>
<input type = "submit" name="search" value = "Search">
</form>