infolink

Tuesday 7 January 2014

Populate Select List PHP Mysql

This tutorial is about to "Populate Select List" in PHP using MySQL. Get values which you want to populate into DropDownList, Combobox or Select List from MySQL through query, and then these values add into Select List using PHP code.
Too many ways to populate or bind the Select List, DropDownList, Combobox.

Steps to Populate Select List:

Here is a very simple steps for this work. 

Step 1:

In a first step create a PHP file like index.php. And write a simple HTML code in it. like this

<html>
<head>
<title>Populate Select List PHP MySQL</title>
</head>
<body>
<select name="select_list" id="select_list">
      <option value="-1">Select...</option>
</select>
</body>
</html>

Step 2:

Now its time to write a query that fetch a values from the database. write this query code between a <select> tag.  i.e:

<html>
<head>
<title>Populate Select List PHP MySQL</title>
</head>
<body>
<select name="select_list" id="select_list">
      <option value="-1">Select...</option>

  <?PHP
                             $sql = "SELECT student_id, student_name FROM tbl_student;                                                     $result = mysql_query($sql);
                            if($result)
                            {
                                while($row=mysql_fetch_array($result))
                                { 
 ?> 
<?PHP
                                }
                            }
?>

</select>
</body>
</html>

Step 3:

Add or display or echo the fetched values between <option> tag. like this:

<html>
<head>
<title>Populate Select List PHP MySQL</title>
</head>
<body>
<select name="select_list" id="select_list">
     
<option value="-1">Select...</option>

  <?PHP
                             $sql = "SELECT student_id, student_name FROM tbl_student;                                                     $result = mysql_query($sql);
                            if($result)
                            {
                                while($row=mysql_fetch_array($result))
                                { 
 ?> 
<option value="<?PHP echo $row["database field name like student_id"]; ?>"><?PHP echo $row["database field name like student_name"]; ?></option>
<?PHP
                                }
                            }
?>

</select>
</body>
</html>

All code is done and the Select List is now Populated. 

No comments:

Post a Comment