| How
to fill a select box from a mysql database
This is a php that shows you
how to fill a select box with values in a mysql database.
First thing you need to do
is create the tables and insert the data for this example to work.
********************************************************************
//drop the follwing in your mysql_front query section
so we create the table and fields
CREATE TABLE TestTable (ID TINYINT (3) DEFAULT '0' NOT NULL AUTO_INCREMENT,
NAME VARCHAR (3) DEFAULT '0', PRIMARY KEY(ID)) TYPE = MyISAM
//it creates a table named TestTable with 2 fields : "ID"
and "Name"
//now drop the follwing in your mysql_front query
section so we have some records
INSERT INTO TestTable VALUES("1","visual basic");
INSERT INTO TestTable VALUES("2","C/C++");
INSERT INTO TestTable VALUES("3","ASP/VBScript");
INSERT INTO TestTable VALUES("4","PHP");
INSERT INTO TestTable VALUES("5","JAVA/JavaScript");
INSERT INTO TestTable VALUES("6","Delphi");
INSERT INTO TestTable VALUES("6","Perl");
This section goes into a php page.
//change the following variables with the appropriate
$host = "yourhostname"
$dbname = "youdatabasename"
$dbpass = "yourdatabasepassword"
$connection = mysql_connect("$host","$dbname","$dbpass");
$db = mysql_select_db("$dbname",$connection);
echo" <select name=\"category\">
"; //start the select box
$results= mysql_query("SELECT ID, Name from
TestTable Order by Cat asc",$connection);
$id = "ID";
$idname = "Name";
echo mysql_error();
if (mysql_Numrows($results)>0) //if there are
records in the fields
{
$numrows=mysql_NumRows($results); //count them
$x=0;
while ($x<$numrows){ //loop through the records
$theId=mysql_result($results,$x,$id); //place each record in the
variable everytime we loop
$theName=mysql_result($results,$x,$idname);
echo "<option value=\"$theId\">$theName</option>\n";
//and place it in the select
$x++;
}
}
echo "</select>"; //close the select
//DONE
|