动态创建下拉列表并填写表单字段

时间:2014-01-13 12:55:19

标签: php

这个完全让我大吃一惊。我对PHP有一个非常基本的了解,因此我的代码是错误的。我的目标是动态创建一个下拉菜单,用户可以从数据库中选择一个我正在工作的条目。从那个选择我有一个表格,我需要自动填充数据库中的选择行数据。有人可以帮忙吗?

(请注意:我知道我的代码非常糟糕,错误等等以及不赞成使用的标签。这都适用于大学项目)

<form id="edit" method="POST" action="">

<?php  

        $con = mysql_connect("localhost","root","");
        if(!$con)
        {
        die('Could not connect: ' . mysql_error());
        }
        mysql_select_db('flexiflash', $con);    

        $query = 'SELECT * FROM event';
        $result = mysql_query($query);

        echo "<select name='events' value='-'>\n";
        echo "<option value='Select event'>Select an event to be changed\n";

        while($row = mysql_fetch_row($result))
        {
        $eventSelect = $row[0];
        echo "<option value='$eventSelect'>$row[1]</option>\n";
        }
        echo "</select>"
        ?>

            <h1>
            <button id="submit" type="submit">Delete</button>
            </h1>




     </form>

上面的代码作品,以下不工作

 <?php
if (isset($_POST['events']))
{
$eventselection = $_POST['events'];
$query = "SELECT * FROM events where event_name = '$eventselection'";   
$row=mysql_fetch_array($query);

}

?>

<form name="editevents" method="POST">

<input type="hidden" value="<?php echo ($row['event_id']); ?>" name="id" /> 

            <h1>
            <label for="eventname">Event Name</label>
            <input id="eventname" type="text" name="eventname" value="<?php echo ($row['event_name']); ?>" />
            </h1>

            <h1>
            <label for="eventtime">Event Time</label>
            <input id="eventtime" type="time" name="eventtime" value="<?php echo ($row['event_time']); ?>" />
            </h1>

</form>

1 个答案:

答案 0 :(得分:0)

从下拉列表中删除value属性,从代码中删除\n。关闭</option>选项的默认Select an event to be changed。在第二个代码块中你缺少mysql_query

 echo "<select name='events'>";

更正后的代码块: -

<form id="edit" method="POST" action="">
    <?php
    $con = mysql_connect("localhost", "root", "");
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('flexiflash', $con);

    $query = 'SELECT * FROM event';
    $result = mysql_query($query) or die(mysql_error());

    echo "<select name='events'>";
    echo "<option value=''>Select an event to be changed</option>";
    while ($row = mysql_fetch_row($result)) {
        $eventSelect = $row[0];
        echo "<option value='$eventSelect'>$row[1]</option>";
    }
    echo "</select>";
    ?>
    <h1>
        <button id="submit" type="submit">Delete</button>
    </h1>
</form>

 <?php
if (isset($_POST['events']))
{
$eventselection = $_POST['events'];
$query = "SELECT * FROM events where event_name = '$eventselection'";  
$result = mysql_query($query);
$row=mysql_fetch_array($result);

}