frequently ask ? : Computers : Programming : Languages : PHP : Common Problems

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 6 people (100%) answered Yes
Recently 2 of 2 people (100%) answered Yes

Entry

How do i extract elements from a database into a Select Form Field

May 29th, 2001 19:57
Onno Benschop, Jan-Borge Landro,


There are two ways you can do this, either make PHP do the building of 
the string, or ask the database to do it:
If you do the concatenation within PHP it looks like this (This is in 
mySQL):
<?
  // connect to the database
  $select = 'SELECT * FROM somewhere' ;
  $dbfResult = mysql_db_query($myDatabase, $select) ;
  $theResult = '<select name=something>' ;
  while ($row=mysql_fetch_array($dbfResult)) {
    $theResult .= '<option value='.$row['idFieldName'].
      '>'.
      $row['fieldValue'].
      '</option>' ;
  }
  $theResult .= '</select>' ;
?>
Did you know that it is actually *much* faster to do this instead, 
because PHP doesn't have to do any string concatenation and parsing, 
you let the database do all the work:
<?
  // connect to the database
  $select = "SELECT CONCAT('<option 
value=',idFieldName,'>',fieldValue,'</option>') AS menu FROM somwhere" ;
  $dbfResult = mysql_db_query($myDatabase, $select) ;
  $theResult = '<select name=something>' ;
  while ($row=mysql_fetch_array($dbfResult)) {
    $theResult .= $row['menu'] ;
  }
  $theResult .= '</select>' ;
?>