Database table: fruitChoice
| userID | apple | orange | banana | grape |
|---|
| x147d | 1 | 0 | 1 | 1 |
| a065b | 0 | 1 | 1 | 1 |
| t992w | 1 | 0 | 1 | 0 |
Query to fetch data from the database:
<cfquery name="getInfo" datasource="myDSN">
select apple,orange,banana,grape
from fruitChoice
where userID = '#session.userID#'
</cfquery>
Query to insert data into the database:
<!--- I use the submit field, not a checkbox, to verify whether the form has been submitted. If you don't check a checkbox, x, then the variable form.x wont exist when the form is submitted --->
<cfif isDefined("form.sbmt")>
<cfset isAppleChosen=0>
<cfset isOrangeChosen=0>
<cfset isBananaChosen=0>
<cfset isGrapeChosen=0>
<cfif isDefined("form.apples")>
<cfset isAppleChosen=1>
</cfif>
<cfif isDefined("form.oranges")>
<cfset isOrangeChosen=1>
</cfif>
<cfif isDefined("form.bananas")>
<cfset isBananaChosen=1>
</cfif>
<cfif isDefined("form.grapes")>
<cfset isGrapeChosen=1>
</cfif>
<cfquery name="saveInfo" datasource="myDSN">
insert into fruitChoice (userID,apple,orange,banana,grape)
values ('#session.userID#',#isAppleChosen#,#isOrangeChosen#,#isBananaChosen#,#isGrapeChosen#)
</cfquery>
</cfif>
And, finally, the form
<form>
<p>
<cfif getinfo.apple EQ 1>
<input type="Checkbox" name="apples" checked>apples
<cfelse>
<input type="Checkbox" name="apples">apples
</cfif>
</p>
<p>
<cfif getinfo.orange EQ 1>
<input type="Checkbox" name="oranges" checked>oranges
<cfelse>
<input type="Checkbox" name="oranges">oranges
</cfif>
</p>
<p>
<cfif getinfo.banana EQ 1>
<input type="Checkbox" name="bananas" checked>bananas
<cfelse>
<input type="Checkbox" name="bananas">bananas
</cfif>
</p>
<p>
<cfif getinfo.grape EQ 1>
<input type="Checkbox" name="grapes" checked>grapes
<cfelse>
<input type="Checkbox" name="grapes">grapes
</cfif>
</p>
<p>
<input type="submit" name="sbmt" value="send">
</p>
</form>