-1

It does not display the selected year from the drop down menu - which is what I am trying to accomplish. It prints up to "You choose" then it doesnt print the year. which is what i want to display.

<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>
psj01
  • 3,075
  • 6
  • 32
  • 63

1 Answers1

1

Try something like this:

<?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. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Community
  • 1
  • 1
Latheesan
  • 23,247
  • 32
  • 107
  • 201