Tuesday, 20 November 2007

Populate a "select" form with a SQL query using coldfusion

In this post I replied to some reader that have asked to me how to populate a select form element with the results of a SQL query using PHP. I received the same question about how to do the same action using Coldfusion.

Image a simple SQL query which get all users' names on a generic database's table, in this case USER, which have two attributes: ID_USER_PK (primary key) and NAME (the user name):

<cfquery datasource="mydatasource" name="getUser">
SELECT * FROM USER
</cfquery>

Now, to display the query's results into a SELECT form you can use this simple code with <cfoutput query="queryName">:

<select name="select" name="userName">
<cfoutput query="getUser">
<option value="#id_user_pk#">#name#</option>
</cfoutput>
</select>



If you have a parameter in input, for example a URL variable, idUser:

#URL.idUser#


...passed to the page in this way:

http://localhost/index.php?idUser=1


<select name="select" name="userName">
<cfoutput query="getUser">
<option value="#id_user_pk#" <cfif #URL.idUser# EQ #id_user_pk#>selected="selected"</cfif>>#name#</option>
</cfoutput>


In this way, you force to set the "selected" attribute, in your SELECT form, equal to "selected" if the current record has an id_user_pk equal to the parameter in input.

Are you a PHP developer? Read here the PHP version of this post

No comments:

Post a Comment