Link to home
Start Free TrialLog in
Avatar of Julian Parker
Julian ParkerFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Processing checkboxes in variable array to update mysql database

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
Avatar of mstrelan
mstrelan
Flag of Australia image

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

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.
Avatar of Julian Parker

ASKER

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>";

I'm not sure I understand what the problem is you're having. Which part of the process is failing?
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??!
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
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.
Thanks Vee_Mod
@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

> 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....
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

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 ;-)
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??
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

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
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.
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?
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?
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

"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
:-)


>> 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...
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

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
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

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.

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 :-)
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.
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.

OK, Good luck with it, ~Ray
Well, we answered the question, as it morphed along, so I think it is suitable to award points. ~Ray
Ray_Paseur,

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

thanks,
a3
I think the most generalized answer is the most useful for this Q

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

Bset regards, ~Ray
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..