有人可以解释为什么我点击提交按钮时下面的代码不起作用?

时间:2014-11-12 17:47:38

标签: php mysql sql

它不会从下拉菜单中显示所选年份 - 这正是我想要完成的。它打印到“你选择”然后它不会打印年份。这就是我想要展示的内容。

<html>
<head><title> Hello </title>

<?php
//code for connection
include 'connect.php';
?>

</head>

<body>
<center>
<br>
<b>welcome</b>
<br>
<?php
$sql1 = "SELECT DISTINCT Year FROM dbnames ORDER BY Year";
$runsql1 = mysql_query($sql1);
if (!$runsql1)
{
    die( "Could not execute sql:" . mysql_error());
}
while($row = mysql_fetch_array($runsql1))
{
             $options .="<option>".$row['Year']."</option>";
}
$years = "<form id='filter1' name='filter1' method='post' action=''>
<select name='filter2' id='filter2'>".$options."</select></form>";
echo "Please choose an year".$years;
?>

<!-- submit button -->
<p><input type="submit" value="Submit"></p>


<?php
echo 'You choose'. $_POST[filter2];
?>

</center>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

<?php

// Connect to DB
include 'connect.php';

// Load Select Options
$year_results = mysql_query("SELECT DISTINCT Year FROM dbnames ORDER BY Year ASC") or die(mysql_error());
$year_options = array();
while ($row = mysql_fetch_assoc($year_results)) {
    $year_options[] = '<option value="'. $row['year'] .'">'. $row['year'] .'</option>';
}

// Handle Post/Selected Year
$selected_year = (!empty($_POST['filter2']) ? $_POST['filter2'] : 'No Year Selected');

?>
<html>
    <head>
        <title> Hello </title>
    </head>
    <body>
    <center>
        <br>
        <b>welcome</b>
        <br>
        <form id='filter1' name='filter1' method='post' action=''>
            Please choose an year: <select name='filter2' id='filter2'>
                <?php echo implode("\r\n", $year_options) ?>
            </select> 
            <input type="submit" value="Submit">
        </form>
        You choose: <?php echo $selected_year ?>
        </center>
    </body>
</html>

Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial