Linked @ del.icio.us

rss icon Mark J. Reeves November, 2007

July 09, 2007 WEBDEV: Build an option list using SQL

After converting another site’s option list to SQL to insert the values into my database, I want to get those values back out into an option list with IDs.

I started with:

<option value="Acura" >Acura</option>
<option value="Alfa Romeo" >Alfa Romeo</option>
<option value="American Motors" >American Motors</option>
<option value="Audi" >Audi</option>
<option value="BMW" >BMW</option>
...

and ran:

INSERT INTO Answer (QuestionId, Text, CreatedDate, ModifiedDate) VALUES (2, 'Acura', NOW(), NOW());
INSERT INTO Answer (QuestionId, Text, CreatedDate, ModifiedDate) VALUES (2, 'Alfa Romeo', NOW(), NOW());
INSERT INTO Answer (QuestionId, Text, CreatedDate, ModifiedDate) VALUES (2, 'American Motors', NOW(), NOW());
INSERT INTO Answer (QuestionId, Text, CreatedDate, ModifiedDate) VALUES (2, 'Audi', NOW(), NOW());
INSERT INTO Answer (QuestionId, Text, CreatedDate, ModifiedDate) VALUES (2, 'BMW', NOW(), NOW());
...

and now have my own set of Answers with their own IDs. I want a select list where each option has an Answer and its ID from my database. To build this list in MySQL*, I use:

SELECT CONCAT('<option value="' , Id , '">' , Text , '</option>') FROM Answer

which results in:

<option value="1">Acura</option>
<option value="2">Alfa Romeo</option>
<option value="3">American Motors</option>
<option value="4">Audi</option>
<option value="5">BMW</option>
...

* In SQL Server you could write:

SELECT '<option value="' + Id + '">' + Text + '<option>' FROM Answer

Read more in the Archives

Mark J. Reeves has been making web sites work since 1998. Currently partnering with designers and firms throughout the Northeast, he pursues front-end development par excellence coupled with experienced database design and development and solid PHP/MySQL or .NET/SQL Server application development. Design-savvy but not a designer, Mark approaches each project enthusiastic about the details and the potential for online success, offering strategic insight on content and marketing decisions.

Mark resides in Salem, Massachusetts with his wife and infant son in a condo that was once a classroom in an 1870s school. With a growing interest in modern architecture, sustainable living and plans to build his own home someday, Mark's also working on a regional community site at ModernHomesNewEngland.com. Get in touch: mjr@c77studios.com.