Code for populating List box from database and using them

Discussion in 'PHP' started by amplifire, May 28, 2010.

  1. #1
    Here is the complete code for beginners for populating a list box with values fetched from database and passing the selected value for display.


    <html>
    <head>
    <title>Untitled Document</title>
    <?php
    $db = mysql_connect("localhost", "root","");
    mysql_select_db("example",$db);
    $sql = "SELECT * FROM students";
    $result = mysql_query($sql,$db);
    while ($myrow = mysql_fetch_array($result))
    {$student[] = $myrow;}
    ?>
    <style type="text/css">
    <!--
    #Layer1 {
    position:absolute;
    width:336px;
    height:26px;
    z-index:1;
    left: 243px;
    top: 15px;
    background-color: #00CCFF;
    }
    -->
    </style>
    </head>

    <body>

    <form id="form1" name="form1" method="post" action="list.php">
    <select name="selectName">
    <?php
    foreach ($student as $stu)
    echo "<OPTION>" . $stu['Name'] . "</OPTION>";

    ?>
    </select>
    <select name="selectAge">
    <?php
    foreach ($student as $stu)
    echo "<OPTION>" . $stu['Age'] . "</OPTION>";
    ?>
    </select>
    <input type="submit" name="get" value="Get" />
    </form>

    <div id="Layer1">
    <?php
    $name=$_POST['selectName'];
    $age=$_POST['selectAge'];
    echo "You selected name and age " . $name . " / " . $age;
    ?>
    </div>
    </body>
    </html>
     
    amplifire, May 28, 2010 IP