?
Solved

Processing checkboxes in variable array to update mysql database

Posted on 2009-04-28
38
Medium Priority
?
1,495 Views
Last Modified: 2013-12-12
Hi All,

I'm having a few issues modifying a booking app.
I'm now working on a form to book multiple resources, the form part is ok but I cant seem to get the right way of processing the check boxes properly.

The user selects a platform type (eg SUN and or DISK) which executes the getsystems.php script to display all the available systems. The user then selects whatever systems are free for use. I then need to process all the checked boxes from the form then update the database using the form options and for each system selected in the reference array (at least thats what I think I need to do...)

Also, assuming the database update is successful I'd then like the form to be closed, it is previously opened with windowopen().
If the database update is not successful then I'd like to display an error message and return to the form.
getsystems.php.txt
addm.php.txt
0
Comment
Question by:jools
  • 17
  • 13
  • 3
  • +1
34 Comments
 
LVL 10

Expert Comment

by:mstrelan
ID: 24255727
Hi,

In you html form you need to make a bunch of checkboxes with the name "systems[]" and ids like "systems_as400" and values like "as400".

eg..


--- html code ----
<input type="checkbox" name="systems[]" id="systems_as400" value="as400" /><label for="systems_as400">AS 400</label>
<input type="checkbox" name="systems[]" id="systems_intel" value="intel" /><label for="systems_intel">Intel</label>
 
 
---- php code ----
if (is_array($_POST['systems'])) {
    foreach ($_POST['systems'] as $system) {
        // do something with each system.
    }
}

Open in new window

0
 
LVL 10

Expert Comment

by:mstrelan
ID: 24255740
Then later on if you need to modify the form you will need to first delete from the db all the systems that are checked before you run the loop above.
0
 
LVL 19

Author Comment

by:jools
ID: 24255837
Thanks but I'm not sure thats it....

The systems, SUN, HP, INTEL etc are processed by the getsystems.php from ajax, this script will list all the available systems like; SUN01, SUN02, INTEL01, INTEL02 etc

Each system checkbox is built using the code from getsystems.php and displayed in the main form. Note that systemref will be the names like SUN01, SUN02 etc etc.

   echo "<div class='reference'><input type='checkbox' name='reference[]' id='reference[]' /><a onmouseover=\"Tip('" . $systemtip . "',TITLE,'SYSTEM INFORMATION',TITLEALIGN,'center',SHADOW,'true')\" onmouseout=\"UnTip()\">" . $systemref . "</a></div>";

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 10

Expert Comment

by:mstrelan
ID: 24255892
I'm not sure I understand what the problem is you're having. Which part of the process is failing?
0
 
LVL 19

Author Comment

by:jools
ID: 24256024
Sorry, I was hoping I could have explained it better....

I can't seem to process the checkboxes named reference[] built using the getsystems.php script and generate the sql code to insert into the database.

By way of an example, assuming that there are no intel servers currently used and that the INTEL checkbox was selected, the getsystems.php script would return 87 Intel Servers available to be booked. If all these servers, INTEL01 thru INTEL87, are then checked by the user and then the user clicked on Add Booking, I would need the form to be processed and the records added into the database like this;
   insert into test_dates values('INTEL01','2009-04-28','2009-04-28','Quickship','1','ACME PLC','Fred Bloggs','CUS')
   insert into test_dates values('INTEL02','2009-04-28','2009-04-28','Quickship','1','ACME PLC','Fred Bloggs','CUS')
   etc etc...

This is where the other options are taken from the form and repeated for every `insert` command for the database.

It's possible to to create an insert statement where all the values are listed and inserted as one sql statement but I also dont know how to build the insert string in this format either.... this may be a better way of doing this as I then only have to connect and insert to the database once.

   eg/
   insert into test_dates values('INTEL01','2009-04-28','2009-04-28','Quickship','1','ACME PLC','Fred Bloggs','CUS'),('INTEL02','2009-04-28','2009-04-28','Quickship','1','ACME PLC','Fred Bloggs','CUS'),('INTEL03','2009-04-28','2009-04-28','Quickship','1','ACME PLC','Fred Bloggs','CUS')

does this make sense??!
0
 
LVL 19

Author Comment

by:jools
ID: 24274484
I'm really stuck with this, I've attached a screen pic of what happens when I select "SUN" from the Additional Systems box and I have selected a number of systems which are currently not booked out.

I have added an alert box to print_r the $_post['reference'] information but it just comes up bank.

The code to print the alert box is included below, it looks OK to me but I'm still relatively new.

One thing I did notice what that if I look at the source code I don't see the check boxes which were generated by the ajax code and getsystems.php.
?>
   <script type 'text/javascript'>alert('<?php print_r($_POST['reference']);?>');</script>
<?php

Open in new window

addm.png
addm-alert.png
0
 
LVL 19

Author Comment

by:jools
ID: 24275191
I've been trying to do a bit of research. I believe some of my problem is ajax not doing a postback of the checkbox options....

This is starting to look like 2 questions, one for getting the postback working and the other for processing the postback data and generating the sql to update the database.

If anyone can confirm my thoughts I'll gladly split the question and ask a related Q for postback.
0
 
LVL 19

Author Comment

by:jools
ID: 24278429
Thanks Vee_Mod
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24280679
@jools: This is annoying but a fact: When a checkbox is not checked, there is NOTHING in the $_POST or $_GET array to indicate its status.  It would have been so easy if the designers of the WWW had given us an indicator like "on" or "off" but that is not the case.

Run this script and experiment with it, and you can see what is afoot.
<?php // RAY_checkboxes.php
error_reporting(E_ALL); // SHOW THE BEHAVIOR OF CHECKBOXES
 
// IF ANYTHING WAS POSTED
if (!empty($_POST["_submit"])) 
{
   echo "<pre>"; var_dump($_POST); echo "</pre> \n";
}
?>
<form method="post">
These checkboxes have names...<br/>
Check or Uncheck Some Boxes Here<br/>
<input name=box1 type="checkbox" value="Box1"><br/>
<input name=box2 type="checkbox" value="Box2"><br/>
<input name=box3 type="checkbox"><br/>
<input name=box4 type="checkbox"><br/>
<br />
These checkboxes are part of the "box" array...<br/>
Check or Uncheck Some Boxes Here<br/>
<input name=box[] type="checkbox" value="ABox1"><br/>
<input name=box[] type="checkbox" value="ABox2"><br/>
<input name=box[] type="checkbox" value="ABox3"><br/>
<input name=box[] type="checkbox" value="ABox4"><br/>
<input type="submit" name="_submit"  value="go" />
</form>

Open in new window

0
 
LVL 19

Author Comment

by:jools
ID: 24280975
> When a checkbox is not checked, there is NOTHING in the $_POST or $_GET array to indicate its status.

I get that, I really do. however, when I click on SUN in the Additional Systems box it executes the getsystems.php script and then populates the SUN fieldset with the available SUN systems, when I select a number of SUN systems then select the "Add Booking" button at the bottom of the screen, it does not seem to return any values for the reference[] array.

What I cant get my head round is why after I've checked the SUN-01 ... boxes and clicked on add there seems to be nothing there. It's like the ajax stuff isnt building the page properly and passing the check boxes as part of the form.

I have to admit, I'm really stuck with this at the moment.

I can probably set up a demo on a friendly web site if it helps....
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24281200
A demo might help and I would be glad to look at it.  Also, you might try something like the code snippet.  Put that in the background script and it will email the contents of $_GET and $_POST to you.  I have not tested it, so beware since I am the King of Typos.  Best, ~Ray
<?php // CAPTURE DATA FROM THE BACKGROUND SCRIPT
 
// START THE OUTPUT BUFFER
ob_start();
 
// GET THE DATA
echo "\nGET: ";
var_dump($_GET);
echo "\nPOST: ";
var_dump($_POST);
 
// CAPTURE THE BUFFERED DATA
$my_text = ob_get_clean();
 
// SEND THE DATA
mail('you@your.org', 'OB DATA', $my_text);

Open in new window

0
 
LVL 19

Author Comment

by:jools
ID: 24281274
I'll see if I can setup a demo for over the next few days....

I'll have a go at your code, not to worry, I'll debug it for you ;-)
0
 
LVL 19

Author Comment

by:jools
ID: 24283779
I've copied the form to a web server here; http://www.nutworks.co.uk/allocate/addm.php

If you select one of the servers it should list the hardware available, from that you just select what kit you want booked out then click on the Add button at the bottom it's supposed to add all the resources with the other form data to the database.

any thoughts as to what is (not) happening??
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24287877
Hi, jools: It would be helpful to add error_reporting(E_ALL) to the action script (the "action script" is the one that processes the data from the "form script") and to look closely at the field called "reference" - it looks like the script has a foreach loop near line 36 that looks at $_POST['reference'] but there is no field in the form named 'reference' - so something may be confused there.

Also I could not find any code that updates a data base.  Can you post that part?

Thanks, ~Ray

0
 
LVL 19

Author Comment

by:jools
ID: 24287990
Hi Ray,

Thanks for having a quick look.

The reference field is added by the javascript/ajax stuff when it executes the getsystems.php script. I've attached the java code so you should be able to see this.

So, in summary, addm.php displays the main form you looked at, clicking on SUN/HP etc executes the getsystems.php which extracts the available systems from the database and adds this information to this form using the javascript/ajax stuff in allocate.js.

I've not written the update database part yet, that is what I am stuck on, I need to be able to process the form before I can do that.

Where exactly would I add the error_reporting to? Is it needed in addm.php or getsystems.php or both?
allocate.js.txt
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24288011
Whenever I am developing or debugging, I would put error_reporting(E_ALL) into every script.  At this point in the application life cycle, you WANT to see the errors.

I think I would also approach this application design a little bit differently.  I do not see a requirement for AJAX.  Instead you can send ALL the data to the page and use onClick() to tell the DOM to reveal or hide the appropriate parts.  That way, you will have everything in the form, even if it is not displayed on the browser window.  And with everything in the form, you will have a fairly straightforward UPDATE statement, and substantially less risk of an "out-of-sync" data base.
0
 
LVL 19

Author Comment

by:jools
ID: 24288891
How do I load all the information into the form when I  dont know what is required in the form until the user selects the date range?
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24289984
I don't know - that's an application design question and I'm not really sure how your application works.  

I was thinking that the AJAX call was needed to get information that could have been known before the page was loaded.  My general strategy would be to send all of the HTML information if possible.  (Things that make it not possible include security or giant data sets or unpredictable factors).  So if the date is one of those unpredictable factors, then you're forced to use AJAX or use two separate pages.

Have you tried to visualize the data with the email-from-background-script yet?
0
 
LVL 19

Author Comment

by:jools
ID: 24290318
Thanks for your assistance Ray, it's much appreciated...

I needed to get round having loads of forms so was told I needed to learn ajax.

You've seen the main form, you just enter the criteria then when you select the additional platform the ajax stuff uses the date ranges to find what systems are free and displays this in the checkboxes which the user can then select as they wish.

What I cant get the form to do is to process is this new data, (the check boxes which have the specific systems listed) and return the values for the checkboxes that have been selected once the user clicks on add booking.

I didnt think it was going to be this difficult to process a form!

I have added the email stuff to the getsystems.php script but it returns exactly what I expect it to, the system and the date ranges.... (see below).

I have noticed that if you look at the page source once the form has listed the systems, you don't see the checkboxes for the systems, just the ajax divs!

I've googled and checked literally hundreds of pages and online books but I cant find a way of getting ajax to generate checkboxes then process the new checkbox values. I have to admit, my ajax/php and java skills are somewhat limited.

I still don't know if ajax is capable of doing what I want or if I need to go back to the multiple form approach which will be easier to code but wont be what the user wants from the interface.

Are there any options for ajax I am missing??

GET: array(3) {
  ["system"]=>
  string(3) "SUN"
  ["frm_startdate"]=>
  string(10) "2009-05-03"
  ["frm_enddate"]=>
  string(10) "2009-05-03"
}
 
POST: array(0) {
}

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24290381
"Are there any options for ajax I am missing??" -- That has got to be the world's most open-ended question ever! ;-)

At its heart, AJAX is just a way of sending data to a backend script and retrieving the stuff that comes back from the script.  That can be a DIV or something much more interesting.  Depending on the handshake between the browser script and the backend script, it can be really elaborate.

I have to leave this for a while, but let me give you a comment on checkboxes that might be useful.  If the checkboxes in a form are NOT CHECKED, they are not present in $_POST, ie, the key that you would expect would have the name of the checkbox is simply not there (!).  This is different from a text input field, which will be present and empty.

I'll look around and see if I can come up with some examples of how to make this work.  It may take a while, but I'll get something back to you here.

Best, ~Ray
0
 
LVL 19

Author Comment

by:jools
ID: 24290426
:-)


>> Depending on the handshake between the browser script and the backend script, it can be really elaborate.
Thats what is worrying me, I dont think my handshake is elaborate enough...

>> If the checkboxes in a form are NOT CHECKED, they are not present in $_POST
Yup, totally understand that! In my case however they are checked, I just cant seem to see the array I assign the values to.

>> I'll look around and see if I can come up with some examples of how to make this work.
...that would be truly marvellous....

While your hunting around, I was wondering... have I explained the way I want the form to work properly? I don't want you spending your time hunting around and it's not quite what I had in mind...

I'll keep hunting as well, I cant give up just yet...
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 24291055
Can't recall where I found this originally, but it is probably attributable to Rasmus Lerdorf of PHP fame.  Read it over and see if it makes sense.  I will try to use it as a basis for a script that will find the checkboxes in a submitted form.
I find a lot of this AJAX stuff a bit of a hype.  Lots of people have
been using similar things long before it became "AJAX".  And it really
isn't as complicated as a lot of people make it out to be.  Here is a
simple example from one of my apps.  
 
/* THE JAVASCRIPT TO CREATE THE AJAX INFRASTRUCTURE */
/* FUNCTION TO CREATE THE BROWSER-DEPENDENT REQUEST OBJECT */
function createRequestObject() 
{
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
    {
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else
    {
        ro = new XMLHttpRequest();
    }
    return ro;
}
 
 
/* FUNCTION TO SEND THE REQUEST */
function sendReq(action) 
{
    http.open('get', 'ajaxprocessor.php?action='+action);
    http.onreadystatechange = handleResponse;
    http.send(null);
}
 
 
/* FUNCTION TO HANDLE THE RESPONSE */
function handleResponse()
{
    if(http.readyState == 4)
    {
        var response = http.responseText;
        var update = new Array();
 
        if(response.indexOf('|' != -1))
        {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];
        }
    }
}
 
 
/* CREATE THE OBJECT */
var http = createRequestObject();
 
/* END OF THE JAVASCRIPT */
 
This creates a request object along with a send request and handle
response function.  So to actually use it, you could include this js in
your page.  Then to make one of these backend requests you would tie it
to something.  Like an onclick event or a straight href like this:
 
<a href="javascript:sendReq('foo')">[Foo]</a>
 
That means that when someone clicks on that link what actually happens
is that a backend request to ajaxprocessor.php?action=foo will be sent.
 
In ajaxprocessor.php you might have something like this:
 
/* THE PHP TO HANDLE THE REQUEST FROM THE FRONT-END SCRIPT */
switch($_GET['action']) 
{
    case 'foo':
      // DO WHATEVER PROCESSING IS APPROPRIATE
      // THEN RETURN A RESPONSE STRING TO handleResponse()
      echo "foo|Foo done";
      break;
      // ETC...
}
 
Now, look at handleResponse.  It parses the "foo|Foo done" string and
splits it on the '|' and uses whatever is before the '|' as the dom
element id in your page and the part after as the new innerHTML of that
element.  That means if you have a div tag like this in your page:
 
<div id="foo">Waiting for Foo</div>
 
Once you click on that link, that will dynamically be changed to:
 
<div id="foo">Foo done</div>
 
That's all there is to it.  Everything else is just building on top of
this.  Replacing my simple response "id|text" syntax with a richer XML
format and making the request much more complicated as well.  Before you
blindly install large "AJAX" libraries, have a go at rolling your own
functionality so you know exactly how it works and you only make it as
complicated as you need.  Often you do not need much more than what I
have shown here.
 
Expanding this approach a bit to send multiple parameters in the
request, for example, would be really simple.  Something like:
 
function sendReqArg(action,arg) 
{
    http.open('get', 'ajaxprocessor.php?action='+action+'&arg='+arg);
    http.onreadystatechange = handleResponse;
    http.send(null);
}
 
And your handleResponse can easily be expanded to do more interesting 
things than just replacing the contents of a div.
 
-Rasmus (Lerdorf?)

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24291346
Well, after some searching and testing, here is what I have.

First the backend script.  You may want to activate line 18 just to test.
<?php // RAY_30_second_AJAX_backend.php
error_reporting(E_ALL);
// CAPTURE DATA FROM THE FOREGROUND SCRIPT
 
// START THE OUTPUT BUFFER
ob_start();
 
// GET THE DATA
echo "\nGET: ";
var_dump($_GET);
echo "\nPOST: ";
var_dump($_POST);
 
// CAPTURE THE BUFFERED DATA
$my_text = ob_get_clean();
 
// SEND THE DATA
// mail('you@your.org', 'OB DATA', $my_text);
 
// RETURN THE DATA TO THE FRONTEND SCRIPT
echo "$my_text";

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24291356
Now the foreground script.  It handles checkboxes and text input.  If you run it with the background script you will see that the "checked" attribute comes through as true or false.

Not that I have anything against AJAX, but there are a lot of moving parts.  I guess that's why many of my colleagues like jQuery!
http://en.wikipedia.org/wiki/JQuery

Best regards, ~Ray
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24291359
Foreground script here...
<?php // RAY_31_second_AJAX_frontend.php
error_reporting(E_ALL);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>RAY_31_second_AJAX_frontend.php</title>
 
<script language="Javascript">
function xmlhttpPost(strURL)
{
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest)
    {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
    {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function()
    {
        if (self.xmlHttpReq.readyState == 4)
        {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}
 
function getquerystring()
{
    var form = document.forms['f1'];
    var box_1 = form.box_1.checked;
    var box_2 = form.box_2.checked;
    var words = form.words.value;
    qstr = 'box_1=' + escape(box_1) + '&box_2=' + escape(box_2) + '&words=' + escape(words);  // NOTE NO '?' BEFORE THIS QUERY STRING
    return qstr;
}
 
function updatepage(str)
{
    document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
Box 1 <input name="box_1" type="checkbox" value="1" /><br/>
Box 2 <input name="box_2" type="checkbox" value="2" /><br/>
Words <input name="words" type="text" value="" />
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/RAY_30_second_AJAX_backend.php?getarg=123+ABC")' />
</form>
 
<div id="result">Awaiting Your Input...</div>
 
</body>
</html>

Open in new window

0
 
LVL 19

Author Comment

by:jools
ID: 24294456
With all the excitement the power supply on the server has popped it's cloggs and gone to the big used hardware store in the sky.... at least I hope it's the power supply and not the motherboard/cpu :-| in anycase, it's not working....

This will obviously delay things a little until I can get it back up and running again. Nw I have to find my special hammer.

0
 
LVL 19

Author Comment

by:jools
ID: 24294462
BTW, with the server down email notifications are also a bit of a problem so I'll get back here as soon as I can :-)
0
 
LVL 19

Author Comment

by:jools
ID: 24353679
test server is back up again...

Can you tell me what your functions getquerystr and update page do so I can understand and see if I can implement into my own code.
0
 
LVL 19

Author Comment

by:jools
ID: 24508812
Ray,

This project is on hold for a few weeks, I've not forgotton but I've been reassigned to complete an audit.

I hope to get back to this as soon as I can, in the mean time thx for your patience.

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24509059
OK, Good luck with it, ~Ray
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24832072
Well, we answered the question, as it morphed along, so I think it is suitable to award points. ~Ray
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 25008469
Ray_Paseur,

  can you help me, by indicating which comments you would accept, using the format:
  http://#a<commentid>

thanks,
a3
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 25008493
I think the most generalized answer is the most useful for this Q

Like this?
http://#a<24291055>

Bset regards, ~Ray
0
 
LVL 19

Author Closing Comment

by:jools
ID: 31575699
Thx, Sorry this took so long. I've not been able to get back to the project. I'm scheduled to get back to this in Sept/Oct but that is way off..
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month17 days, 1 hour left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question