29 Jan 2014

Fill data from Database to Listbox (PHP)

What you need:
Database connection

 1. Save your Select into a variable

 


With this Select we can get all (*) the data from the database table called "Nations". I saved the Query into a variable called $sql.


1.1 Send your Query and check if it was successful

 

mysql_query($sql) sends a request to the Server with the Select variable we created above. Add "or die" to check if we get any errors. The request will be automatically canceled and the message inside the brackets of die( ) will be saved into $result. If the query is successful we will get all the data from "Nations" as mentioned above.


2. Creat the head of the Listbox

 




If you set no size it will become a drop down list.

3. Get the first row of $result






Since $result can has more than one Nation in it, we have to read each row separated to get every single Nation out of it. With mysql_fetch_assoc() this is possible.


4. Fill data from Database to Listbox

 

 

 

 


As you can see we have to use a while loop until our condition is false. We write every Nation's name to the Listbox between the 'option' tags and get the next Nation with mysql_fetch_assoc(). When our $nation is empty it will automatically leave the while loop and close the Listbox. 

No comments:

Post a Comment