Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Mysql table field values in Select box

Tags:

html

php

mysql

I want to display the Mysql table Filed values in selectbox. I tried the following code to display. But it normally display the specified field values in echo function and not in select box. I don't know where I mistake.

 $con = mysql_connect("localhost","root","root");
 $db = mysql_select_db("Time_sheet",$con);
 $get=mysql_query("SELECT Emp_id FROM Employee");
 while($row = mysql_fetch_assoc($get))
{
echo ($row['Emp_id']."<br/>");
}

<html>
<body>
<form>
 <select> 
<option value = "<?php echo($row['Emp_id'])?>" ><?php echo($row['Emp_id']) ?></option>
</select>
</form>
</body>
</html>

Also the field values must be display in ascending order. How to achieve..

like image 596
Prusothaman Varatharaj Avatar asked Jan 17 '13 05:01

Prusothaman Varatharaj


2 Answers

<?php
$con = mysql_connect("localhost","root","root");
 $db = mysql_select_db("Time_sheet",$con);
 $get=mysql_query("SELECT Emp_id FROM Employee ORDER BY Emp_id ASC");
$option = '';
 while($row = mysql_fetch_assoc($get))
{
  $option .= '<option value = "'.$row['Emp_id'].'">'.$row['Emp_id'].'</option>';
}
?>
<html>
<body>
<form>
 <select> 
<?php echo $option; ?>
</select>
</form>
</body>
</html>

PS : On a sidenote, please stop using mysql_* functions. Take a look at this thread for the reasons.

like image 53
asprin Avatar answered Sep 30 '22 00:09

asprin


You can easily do it like this

$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");

<html>
<body>
<form>
    <select> 
    <option value="0">Please Select</option>
        <?php
            while($row = mysql_fetch_assoc($get))
            {
            ?>
            <option value = "<?php echo($row['Emp_id'])?>" >
                <?php echo($row['Emp_id']) ?>
            </option>
            <?php
            }               
        ?>
    </select>
</form>
</body>
</html>
like image 23
Muhammad Raheel Avatar answered Sep 29 '22 22:09

Muhammad Raheel