如何在PHP中的mySQL表中填充下拉框

时间:2014-04-03 21:47:10

标签: php html mysql

我有一个带有驱动程序表的mysql数据库,其中包含以下字段: ID 用的名字 姓 国籍 TEAM_ID

我正在尝试创建一个PHP,它检索每个驱动程序的名称和ID,然后输出应该包含一个HTML表单,其中应包含一个提交按钮和一个下拉框。下拉输入应包含驱动程序名称,当按下提交按钮时,表单应通过GET方法提交给另一个名为task4.php的php。

我已经开始做一些代码但无法完成它。

<?php
// Create connection
$con=mysqli_connect("hostname","login","password","db_name");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT forename, surname, id FROM Drivers);

$options="";

while ($row=mysql_fetch_array($result)) {
$id=$row["forename"];
$thing=$row["surname"];
$options.="OPTION VALUE=\"$id\">".$forename;
}
?>

请帮帮我

3 个答案:

答案 0 :(得分:0)

当您从SELECT语句中获得结果时,它的格式为$row['columnName']

$result = mysqli_query($con, "SELECT forename, surname, id FROM Drivers");

$options="<select>";

while ($row=mysqli_fetch_array($result)) {

    $options .= '<option value="'.$row["id"].'">'.$row["forename"].' '.$row["surname"].'</option>';

}

$options .= '</select>';

echo '<form action="task4.php">';
echo $options;
echo '<input type="submit" name="submit">';
echo '</form>';

答案 1 :(得分:0)

<?php
// Create connection
$con = mysqli_connect("hostname","login","password","db_name");

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
$query = 'SELECT id, forename, surname FROM Drivers';

if($result = mysqli_query($con, $query))
{

    $options="";

    while ($row=mysqli_fetch_array($result)) 
    {
        $id=$row['id'];
        $surname=$row['surname'];
        $forename = $row['forename'];
        $options.="<option value='$id'>" . $forename . ' ' . $surname . '</option>';
    }
    echo '<form name="form1" action="task4.php" method="get">';
        echo '<select name="dropdown">';
            echo $options;
        echo '</select>'</br>;
        echo '<input type="submit" value="Send">';
    echo '</form>';
}
?>

答案 2 :(得分:0)

这应该会让你开始。

<?php
// Create connection
$con=mysqli_connect("hostname","login","password","db_name");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL:" . mysqli_connect_error();
}    

$result = mysqli_query($con, "SELECT forename, surname, id FROM Drivers);
?>

<form action='form4.php' method='get'>
<select name='driver_name'>

<?php
while ($row=mysqli_fetch_array($result)) {
echo "<option value='{$row['id']}'>".$row['forename']." ".$row['lastname']."</option>";
}
?>
</select>
<input type='submit' name='submit' value='Submit'>
</form>