Dynamic Dropdowns in PHP
When developing a simple web application for a client recently I had to include a dropdown list box on an input form to allow the user to choose a specific location. I wanted to make the application as flexible for future development as possible So rather than hardcode the list into HTML I created a table in a MySQL database. This allows the client to add new locations when they require and have the list automatically refresh with those changes. The code is I used is as follows:
<select name="list" id="list">
<?php
// Connects to the MySQL database server
$link=mysql_connect("server","user","password");
// Error Checking: Displays the connection error
if (!$link){
  die("Could not connect: ".mysql_error());
}
// Selects the database to use
mysql_select_db("dbName", $link);
// Performs the SQL query
$sql="SELECT * FROM table ORDER BY tableID";
$result=mysql_query($sql);
// Populates the listbox. Loops until the array is empty.
while($line=mysql_fetch_array($result)){
  // This bit outputs each line of the array.
  echo "<option value=$line[tableID]>$line[Name]</option>";
}
?>
</select>
Just copy and paste the above code into your PHP document and change the variables to suit.
admin
Internet Marketing News
All News
Design News
Development News
Marketing News
Keep up to date with MonkeyFish