Click here to Skip to main content
Click here to Skip to main content

Using checkboxes to update multiple database entries

By , 10 Mar 2002
 

Introduction

I have seen a lot of people struggle with this sort of thing, so after having written a solution for a friend of mine, I decided that it would be useful to people to see this way of doing things.

As an example I will keep things very simple, the problem is this:
You have a table (called aTable in this example), with a primary key column named id and a bit (yes/no for access people) field called active. What you want to do is display a form with a checkbox for each record in aTable and allow the user to update the active field for every record in one submission (where active will be set to 1 if the checkbox is ticked and set to 0 if it is unticked). Obviously you could simplify things by having each record in it's own form but this would make updating large numbers of records a real pain.

This is my solution to the problem. Below is an example of the HTML generated for the form:

<form name="form1" action="chkBoxes.asp" method="post">
 <table>
  <tr>
   <td>Checkbox1:</td>
   <td><input type="checkbox" name="chkBox" value="1"></td>
  </tr>
  
  <tr>
   <td>Checkbox2:</td>
   <td><input type="checkbox" name="chkBox" value="2"></td>
  </tr>
  
  <tr>
   <td>Checkbox3:</td>
   <td><input type="checkbox" name="chkBox" value="3"></td>
  </tr>
  
  <tr>
   <td>Checkbox4:</td>
   <td><input type="checkbox" name="chkBox" value="4"></td>
  </tr>
  
  <tr>
   <td>Checkbox5:</td>
   <td><input type="checkbox" name="chkBox" value="5"></td>
  </tr>
  <tr>
   <td colspan="2"><input type="submit" value="go"></td>
  </tr>
 </table>
 <input type="hidden" name="allBoxes" value="1,2,3,4,5">
</form>

The value of the checkboxes would be set as the id from aTable. As you can see the checkboxes are all named the same thing. This simplifies retrieving the results as otherwise we would have to do some dynamic request.form calls which are really ugly to look at.

Ok so that's our form, now what do we do with it? Well let's take a look at the first bit of code.

'get the array with all of the checkbox id's
arrAll = split(Request.Form ("allBoxes"), ",")
 
'get the array with the id's that were ticked
arrVals = split(Request.Form ("chkBox"), ",")

All we do here is fill two arrays with the results from our form. The first array arrAll is filled from the allBoxes hidden input which as you can see in the form code is a string containing all of the values for the checkboxes.The second array arrVals is filled with the checkboxes that were checked (remember if a checkbox is not checked it does not submit a value in the form post.). All simple stuff so far, now we generate the SQL statement which updates the values that were ticked.

strSql = ""
strSql = strSql & "UPDATE aTable SET active = 1 WHERE "

'loop through the checkboxes which were ticked
for i = 0 to ubound(arrVals)
 if i = 0 then
  strSql = strSql & "id = "& arrVals(i)
 else
  'only add the " AND " if this is not the first value
  strSql = strSql & " AND id = "& arrVals(i)
 end if
next

Response.Write strSql & "<hr>"

What we do here is simply loop through the checkbox values which are contained in the arrVals array. If you remember these are the values which were checked so the SQL statement is setting the active column to 1 (i.e. make it active). Still very simple, next we need to generate the SQL statement which marks the unchecked values as inactive.

'dimension the array to the size we need
redim arrInActive(ubound(arrAll) - ubound(arrVals))

'set our indexer variable
IDX = 0

'loop through all the checkbox values
for i = 0 to ubound(arrAll)
 'a boolean value to check if we match or not
 bThere = false
 'loop through the values which were submitted
 for z = 0 to ubound(arrVals)
  'if it is found then set the boolean to true
  'this is so we don't add it to the new array
  if trim(arrVals(z)) = trim(arrAll(i)) then
   bThere = true
  end if
 next 
        'if it wasn't in the submitted array (i.e. it wasn't checked)
 if bThere = false then 
  'add the value to the new array
  arrInactive(IDX) = arrAll(i)
  'increment our indexer
  IDX = IDX + 1
 end if
next

strSql = ""
strSql = strSql & "UPDATE aTable SET active = 0 WHERE "
'loop through the array which holds the values that were NOT ticked
for i = 0 to ubound(arrInactive)
 if arrInactive(i) <> "" then
  if i = 0 then
   strSql = strSql & "id = "& arrInactive(i)
  else
   'only add the " ADD " if this is not the first variable
   strSql = strSql & " AND id = "& arrInactive(i)
  end if
 end if
next

Response.Write strSql

This code segment is a bit more complicated. The first thing is to dimension an array to store the values which were not checked. Basically what follows is to loop through all of the values contained in the arrAll array, then for any values which do not appear in the arrVals array (i.e. they were not checked) add them to the arrInactive array. Finally we loop through this newly populated array to generate the SQL statement.

Look at the comments in the code for a better explanation of each section of code.

You should find this code quite simple to modify so that you can use it with a database, I chose to write it like this so that the concepts would be clearer. If you are struggling to implement this in the context of the database, then just let me know and I'll try and help you out.

I hope this helps some people out with this potentially murky problem. Good luck and as allways suggestions and constructive criticisms are very much welcome.

Inspired by an article by Bill Wilkinson on aspFaqs.com. I thought Bill's method was a bit overly complex so I decided to post my solution (although Bill's article is probably better written).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Torsten Mauz
Web Developer
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalworking but not updating the active field in dbasememberphil666711 Oct '07 - 18:58 
Hi everyone,
have got the script working and it is writing the chkbox options to screen but not to the database. Can you please suggest any reason for this as i am new at asp and still trying to find my feet.
Many thanks in advance.
Tommy
GeneralConnecting to a databasememberphil66679 Sep '07 - 20:52 
Hi,
very new to asp and i understand the explanation of how it works but the application connectivity to a database escapes me. I have been "chain learning" the UPDATE sql command but can't apply it to this situation when i have to apply variables to this. Please help get me started!!!!
Many thanks
Questionstill stumpped!memberlister23 Oct '06 - 1:10 
i have looked at this code for a bit now and am still having trouble downloading it and running it, it prints out whats been ticked and hasnt been but doesn't seem to update the database, reading the other comments there are a few solutions but i do not know how to intergrate them in to the original code. Any help will be s great help.
 
Thanks
 
.: Lister :.

GeneralAccess seems to be limited to 95 recordsmembercodepuss7 Jan '06 - 21:49 
It you have a really long table, an access database will allow updates to no more than 95 records. That sucks!Mad | :mad:
GeneralSimple solution...sussAnonymous30 Jul '04 - 0:30 
This seems very long winded and unnecessary....
 
For your asp code try...
 

<%
strSQL = "UPDATE aTable SET active = 0"
publishVals = Request.Form("chkBox")
If Not IsEmpty(publishVals) Then
strSQL = "UPDATE aTable SET active = 1 WHERE id IN (" & publishVals & ")"
Conn.Execute strSQL
End If

 
There, very simple solution. Works and handles all the cases that other people have been struggling with...
GeneralRe: Simple solution...membermorphias16 Jul '05 - 21:18 
I know this is an old thread but,
Thank You.
 
I was just reading this because I was bored.
I am using a For and Next to do this, you just took my code from 30 lines to about 8, thanks Smile | :)
I was using my code in over 10 places on my website. Blush | :O
QuestionRe: Simple solution...memberlister23 Oct '06 - 1:10 
where does this go in the code?? do u have to take out both update statements?
 
.: Lister :.

GeneralYou really should just use an IN clause...sussAnonymous17 May '04 - 8:01 
...that way you don't even have to do any looping.
GeneralTorsten Mauz !! Help me with multiple checkboxmemberGuidingstar17 Mar '04 - 17:38 
HI Torsten Mauz , I don't know how to contact u! I try out according your article but this is not working !I am using SQL and can't execute update with AND operator !! ANy help ??Pls contact me at nicky_zz@yahoo.com !! Anyone who willing to help me also I will appreciate !! Thanks !
strSql = ""
strSql = strSql & "UPDATE NoFaxCompanies SET INV_SSTATE ='"&chg_status&"' WHERE "
'loop through the array which holds the values that were NOT ticked
for i = 0 to UBound(company_name)
if i = 0 then
strSql = strSql & "INV_CONO ='"&company_name(i)&"'"
else
'only add the " ADD " if this is not the first variable
strSql = strSql & " AND INV_CONO = '"& company_name(i)&"'"
end if
next

Response.Write strSql
set rs2 = conn.Execute(strSql)
GeneralRe: Problems with the script solved...suss_Milhouse2719 Mar '04 - 14:54 
Hey guys,
I worked out a working version of the script, using OR instead of AND in the WHERE clause.
 
But there are still 2 problems:
 
1. If you tick all checkboxes you'll get the known WHERE Clause error!
 
2. If you untick all checkboxes the values don't change all to 'false'!
 
I would be more than thankful if s1 could finally help me with that!
 
Here's the code including the HTML part:
 
- Table: Test (incl. ID, active, user)
- Checkboxes: active
- Database Connection: MM_connTest_STRING
 
-------------------------------------------
 
<% If Request.Form("active") <> "" Then %>
<%
'get the array with all of the checkbox id's
arrAll = split(Request.Form ("allBoxes"), ",")

'get the array with the id's that were ticked
arrVals = split(Request.Form ("active"), ",")
 
strSql = ""
strSql = strSql & "UPDATE Test SET active = 1 WHERE "
 
'loop through the checkboxes which were ticked
for i = 0 to ubound(arrVals)
if i = 0 then
strSql = strSql & "ID = "& arrVals(i)
else
'only add the " AND " if this is not the first value
strSql = strSql & " OR ID = "& arrVals(i)
end if
next
 
set commTest = Server.CreateObject("ADODB.Command")
commTest.ActiveConnection = MM_connTest_STRING
commTest.CommandText = strSql
commTest.CommandType = 1
commTest.CommandTimeout = 0
commTest.Prepared = true
commTest.Execute()
 
'dimension the array to the size we need
redim arrInActive(ubound(arrAll) - ubound(arrVals))
 
'set our indexer variable
IDX = 0
 
'loop through all the checkbox values
for i = 0 to ubound(arrAll)
'a boolean value to check if we match or not
bThere = false
'loop through the values which were submitted
for z = 0 to ubound(arrVals)
'if it is found then set the boolean to true
'this is so we don't add it to the new array
if trim(arrVals(z)) = trim(arrAll(i)) then
bThere = true
end if
next
'if it wasn't in the submitted array (i.e. it wasn't checked)
if bThere = false then
'add the value to the new array
arrInactive(IDX) = arrAll(i)
'increment our indexer
IDX = IDX + 1
end if
next
 
strSql = ""
strSql = strSql & "UPDATE Test SET active = 0 WHERE "
'loop through the array which holds the values that were NOT ticked
for i = 0 to ubound(arrInactive)
if arrInactive(i) <> "" then
if i = 0 then
strSql = strSql & "ID = "& arrInactive(i)
else
'only add the " ADD " if this is not the first variable
strSql = strSql & " OR ID = "& arrInactive(i)
end if
end if
next
 
set commTest = Server.CreateObject("ADODB.Command")
commTest.ActiveConnection = MM_connTest_STRING
commTest.CommandText = strSql
commTest.CommandType = 1
commTest.CommandTimeout = 0
commTest.Prepared = true
commTest.Execute()
 
Response.Redirect "test_multiple.asp"
%>
<% End If %>
<%
Dim rsActive
Dim rsActive_numRows
 
Set rsActive = Server.CreateObject("ADODB.Recordset")
rsActive.ActiveConnection = MM_connTest_STRING
rsActive.Source = "SELECT * FROM Test"
rsActive.CursorType = 0
rsActive.CursorLocation = 2
rsActive.LockType = 1
rsActive.Open()
 
rsActive_numRows = 0
%>
 
<%
Dim Repeat1__numRows
Dim Repeat1__index
 
Repeat1__numRows = -1
Repeat1__index = 0
rsActive_numRows = rsActive_numRows + Repeat1__numRows
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
 
<body>
<form name="Test" action="test_multiple.asp" method="post">




Checkbox1: <input type="checkbox" name="active" value="1">
Checkbox2: <input type="checkbox" name="active" value="2">
Checkbox3: <input type="checkbox" name="active" value="3">
Checkbox4: <input type="checkbox" name="active" value="4">
Checkbox5: <input type="checkbox" name="active" value="5">
<input type="submit" value="go">
<input type="hidden" name="allBoxes" value="1,2,3,4,5">
</form>

<%
While ((Repeat1__numRows <> 0) AND (NOT rsActive.EOF))
%>
<%
Repeat1__index=Repeat1__index+1
Repeat1__numRows=Repeat1__numRows-1
rsActive.MoveNext()
Wend
%>
<%=(rsActive.Fields.Item("ID").Value)%> <%=(rsActive.Fields.Item("active").Value)%> <%=(rsActive.Fields.Item("user").Value)%>
</body>
</html>
<%
rsActive.Close()
Set rsActive = Nothing
%>
Generaluncheck allmemberSanne Pit5 Feb '03 - 6:31 
The script gives an error when all ar unchecked. The "WHERE" is in a wrong place.
 

GeneralHeLp pLz~!memberDarkSith21 Aug '02 - 16:38 
I need help in coding my checkboxes to post to another asp page. The checkboxes are of the same name as it is dynamic and is printed whenever there is a row. Here is the code of the page before i post to the next page to Update the MS Access database:
<%@ Language=VBScript %>
<% Option Explicit %>
<!-- #INCLUDE FILE="MappingDatabase.asp" -->
<%

Dim team_name
team_name=Request.Form("team_name")
Dim sqlst
sqlst = "SELECT * FROM meetings WHERE team_name='"& team_name & "'"
Dim ViewCase
Set ViewCase = Server.CreateObject ("ADODB.RecordSet")
ViewCase.Open sqlst , objConn

 
%>
<FORM ACTION="http://isd-loan-unit/meeting3.asp?team_name=<%=ViewCase("team_name")%>" METHOD="POST">


<%
 
Do While Not ViewCase.EOF

%>


<%

Loop
ViewCase.Close
set ViewCase = nothing
objConn.Close
set objConn = nothing

%>
Team Name Meeting Number Done meeting?
<%=ViewCase("team_name")%>  <%=ViewCase("meeting_no")%> 
<input type="checkbox" name="concluded_meeting" value="True" <%If ViewCase("concluded_meeting")="True" Then Response.Write "checked"%>>
 
<%
ViewCase.MoveNext

%>


<input type="submit" name="Submit" value="Submit">
<input type="hidden" name="checkValue" value="1,2,3,4,5">

</form>
The second page where it is supposed to split the array and update the database is here:
 
<%@ Language=VBScript %>
<% Option Explicit %>
<!-- #INCLUDE FILE="MappingDatabase.asp" -->
<%
dim team_name
dim bThere
dim z
dim IDX
dim arrAll
dim arrVals
dim concluded_meeting
dim strSql
Dim objRS
Dim i
Dim ViewCase
Set objRS = Server.CreateObject ("ADODB.RecordSet")
objRS.Open "meetings", objConn, , 3


team_name=Request.QueryString("team_name")
arrAll = split(Request.Form ("concluded_meeting"), ",")
arrVals = split(Request.Form ("checkValue"), ",")
strSql = ""
strSql = strSql & "UPDATE meetings SET concluded_meeting = 'True' WHERE team_name='"& team_name & "' AND"
 
for i = 0 to ubound(arrVals)
if i = 0 then
strSql = strSql & "meeting_no = "& arrVals(i)
else

strSql = strSql & " AND meeting_no = "& arrVals(i)
end if
next
 

 
redim arrInActive(ubound(arrAll) - ubound(arrVals))
 
IDX = 0
 
'loop through all the checkbox values
for i = 0 to ubound(arrAll)
'a boolean value to check if we match or not
bThere = false
'loop through the values which were submitted
for z = 0 to ubound(arrVals)
'if it is found then set the boolean to true
'this is so we don't add it to the new array
if trim(arrVals(z)) = trim(arrAll(i)) then
bThere = true
end if
next
'if it wasn't in the submitted array (i.e. it wasn't checked)
if bThere = false then
'add the value to the new array
arrInactive(IDX) = arrAll(i)
'increment our indexer
IDX = IDX + 1
end if
next
 

if bThere = false then
'add the value to the new array
arrInactive(IDX) = arrAll(i)
'increment our indexer
IDX = IDX + 1
end if
 

 
strSql = ""
strSql = strSql & "UPDATE meeting SET concluded_meeting = 'False' WHERE team_name='"& team_name & "' AND "
'loop through the array which holds the values that were NOT ticked
for i = 0 to ubound(arrInactive)
if arrInactive(i) <> "" then
if i = 0 then
strSql = strSql & "concluded_meeting = "& arrInactive(i)
else
'only add the " ADD " if this is not the first variable
strSql = strSql & " AND concluded_meeting = "& arrInactive(i)
end if
end if
next
 
Response.Write strSql
%>
 
Meeting Updated

<%
objRS.Close
set objRS = nothing
objConn.Close
set objConn = nothing

%>
There are 3 fields in the database. team_name, meeting_no and concluded_meeting. Team_name is text, meeting_no is an integer and concluded_meeting is a Yes/No type. Max number for meeting_no is 20 although in future it might be update to 30 or more.Could someone plz help? It wld be greatly appreciated~!Confused | :confused:

GeneralThe SQL is bogusmemberDancebert19 Jun '02 - 21:12 
The code produced the following SQL
   UPDATE aTable SET active = 0  
   WHERE id = 1 AND id = 3 AND id = 7 ...
 
This will not update any records because each record has a single ID value, so the WHERE clause will always be false.
Instead, the Where clause should be:
   WHERE id = 1 OR id = 3 OR id = 7 ...
 

 

 

GeneralRe: The SQL is bogusmemberTorsten Mauz19 Jun '02 - 22:52 
Smile | :) a good point well made. You're the first one to spot that Smile | :)
 
I'll update the code..
GeneralRe: The SQL is bogusmemberSannepit28 Jan '03 - 6:59 
Hmmm.. I tried for hours to get it working, untill i saw your reply...
 
Thank you!!! I think the Author should change his code :>
Generaluseful when u dont have stored procmemberHoratiu CRISTEA21 Mar '02 - 1:44 
ur method is usefull when u dont have access to stored procedures.
updating multiple records like u said could be done in a very simple method by using a stored procedure.
using ur example u have a table aTable with a collumn active. like u said the records will be displayed and all the checkboxes having the same name coz when u request it u will get a string with the selected values separated by ", " (a comma and a space)
strValues = Request.Form ("chkBox")
strValues = Replace( strValues, ", ", "|" )
strValues = "|" & strValues & "|"
that code will replace ur string with the checked records IDs which would look like "1, 2, 5, 10, 23" to something like "|1|2|5|10|23|".
now all u got to do is to make a SP(stored procedure) that will have an input parameter ur string with the records IDs and in this SP first u will set all the records to 0 with:
UPDATE aTable SET active = 0
Then u will set the active to 1 for those record IDs that r in the string. That string will be repesented in the SP by the variable @n_Values
UPDATE aTable
SET active = 1 
WHERE
    CHARINDEX('|' + CONVERT(varchar, id) + '|', @n_Values) > 0
and u put those statements in 1 transaction and u fixed ur update all the records in 1 move Smile | :) I vould prefer this aproach if i would have access to SQL Server. but if i would use MS Access or other DB like that i would use ur method.
 
---------------
Horatiu CRISTEA
GeneralRe: in MS Access is like this:memberHoratiu CRISTEA8 Jun '02 - 3:19 
strSql = ""
strSql = strSql & "UPDATE aTable SET active = 1 WHERE "
strSql = strSql & "inStr('" & strValues & "'," & "'|' & Id & '|')>0"
 
so u dont need to use the split and then the array. i think its easier and less code to write.
 
---------------
Horatiu CRISTEA

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 11 Mar 2002
Article Copyright 2002 by Torsten Mauz
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid