Solved

php array and checkboxes

Posted on 2007-11-17
13
2,835 Views
Last Modified: 2008-02-01
To transform a variable into an array from a form with php you add a pair of square bracket []

ex.<input type="text" name="Record_id[]" value="1">
     <input type="text" name="test[]">

So on the receiving script (let say to do an insert in a db) I can loop thru the array and insert every record as needed.

ex. $id = $_POST['Record_id'];

                      for ($i = 0; $i < sizeof($id); $i++)
                                {
                             $test = $_POST['yesy'][$i];
                               script to insert here
                                 }

so I can loop thru the array and insert as many row as I want, the form being dynamicaly created it could be 1 to a few dozen insert.

This is a bare bone example of course the form has quite a few more input fields. Everything works great till you have a checkbox in the form.

The problem is the checkbox is not submitted with the form if it is not checked.

So if I have 3 forms to submit at once and one of the checkbox is not checked it is not being sent which in turn leave an empty space in the array and the following checkbox that is checked fall i the empty space and get inserted with he wrong id.

ex.

<input type="text" name="username[]" value="Bob>
<input type="checkbox" name="member[]" value="1"> let say we tick this one

<input type="text" name="text[]" value="Mark">
<input type="checkbox" name="member[]" value="1">

<input type="text" name="text[]" value="Sophie">
<input type="checkbox" name="member[]" value="1"> and this one

On the insert script you end up with

username[0] Bob
member[0] member

username[1] Mark
(checkbox not submitted)

username[2] Sophie
member[1] member --------> this will fill the empty spot with Mark
 
The end result on the insert is

Bob is a member //correct
Mark is a member //incorrect
Sophie is not a member //incorrect

So the question is obvious how can I ensure that the checkboxes will be assign to the right record even if some are not checked in between?
0
Comment
Question by:gamebits
  • 6
  • 4
  • 3
13 Comments
 
LVL 21

Expert Comment

by:nizsmo
Comment Utility
Hi gamebits

because all your checkboxes have the same name (hence the array member[]) it is hard to differentiate between which checkox belongs to what name, as there is nothing to identify this.

As a suggestion, in place of the checkboxes, I would replace them with a pair of radiobuttons, one labelling YES and the other NO, symbolizing if the user is a member.
This would solve your problem of someone not checking the box, as by default something is already checked and you cannot "uncheck" a radiobutton.

The only thing you will have to look out for is that the pair of radio button has to have the same name, however each different pair will have to have different names.

An alternative to the radio buttons of course, is to modify what you have above, but changing the checkbox's name attribute, so that every one of them will have a unique name.

I know my suggestions are not perfect, but to me it seems you need a way to uniquely identify which checkbox belongs to which name, othewise you will end up with the problem you are having now.
<p>Name: 

  <input type="text" name="text[]" value="Mark">

  <br />

  Is Member: 

  <input name="isMember1" type="radio" value="1" checked="checked"/> 

  YES | 

  <input name="isMember1" type="radio" value="0" />

NO</p>

<p>Name:

  <input type="text" name="text[]2" value="Sophie" />

  <br />

Is Member:

<input name="isMember2" type="radio" value="1" />

YES |

<input name="isMember2" type="radio" value="0" checked="checked"/>

NO</p>

Open in new window

0
 
LVL 20

Expert Comment

by:steelseth12
Comment Utility
<input type="text" name="username[]" value="Bob>
<input type="checkbox" name="member[]" value="1">

<input type="text" name="text[]" value="Mark">
<input type="checkbox" name="member[]" value="2">

<input type="text" name="text[]" value="Sophie">
<input type="checkbox" name="member[]" value="3">

You know that the checkbox with value 1 belongs to username[0] with value 2 to username[1] etc
0
 
LVL 28

Author Comment

by:gamebits
Comment Utility
Ok may be I should explain a more specific situation, the generic one that I posted does not explain it properly.

I'm building an application for coin collectors, there is database will all the Canadian coins, the user select a denomination, let say cent, I then display a table with some info like date mintage etc.

I have a checkbox for each cent displayed in the table and 3 buttons "details" "value" "add it", the user select one or more cent and click on a button, "details" give him more details on the coin(s) he selected
                                                               "value" give him the value
                                                        and "add it" give him the chance to insert these coins in his own personal db.

This is where I'm getting into a problem, if the user select let say 3 coins to insert into his personal db the page display the basic information about the coins plus a few more fields for him to fill

grade, date purchased, price paid, comments

I don't know if you collect coins or not but here there is companies specialized in grading the coins when they do that they seal the coin in a plastic container called a "slab", so in my form I have a checkbox with the label "slabed" if the user tick this box a dropdown appear with a list of all the companies and also a field where the user can enter the registration number.

If 2 of the coins the user want to insert are slabed and one of them is not the unchecked checkbox mess up the insert.

I guess I could use radio button to do that but it realy look better with the checkbox it doesn't matter to me if the solution involve javascript or not.

I haven't wrote the script to pull the information from the user's table yet but you could see the way it work to insert here

http://www.worldcoinsdatabase.com/NEW_WCDB/topmenuswitcher.php?dest=dbcanada&subdest=cdncircoins

It is in development so most of the link are not working yet.
0
 
LVL 20

Expert Comment

by:steelseth12
Comment Utility
gamebits you know the PK of the coin ... give the value of the check the PK of the coin and you know which coins is supposed to be slabed and which are not
0
 
LVL 20

Accepted Solution

by:
steelseth12 earned 250 total points
Comment Utility
another way would be to use multidimensional arrays

e.g
<input  value='' type=text name="coin[5][date_purchased]" size=10>
<input type="checkbox" name="coin[5][slabed]" value="1"  >

Where 5 is the PK of the coin

you can then do

foreach($_POST["coin"] as $key=>$value) {

       $coins[$key]["date_purchased"] = $_POST["coin"][$key]["date_purchased"];
      $coins[$key]["slabed"] = $_POST["coin"][$key]["slabed"];


}

and now you have an empty entry for the checkbox
0
 
LVL 20

Expert Comment

by:steelseth12
Comment Utility
A third way to do it ... dont like this one ... is to use a hidden field <input type="hidden" name="slabed[]" value="0"  > to send the 0 value if the checkbox is not ticked ...

Is this helping ? Im running out of ideas.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 28

Author Comment

by:gamebits
Comment Utility
Don't know yet, working on the first idea still, it's easy to assign the PK of the coin as a value for the checkbox not sure yet how to use it on the receiving end.

I already try the hidden field idea for some reason it did not work no matter what sequence I used, checked ,unchecked, I always end up with alternate 0 and 1 (beside the fact it did not work, why don't you like this option?)
0
 
LVL 20

Expert Comment

by:steelseth12
Comment Utility
its more of a bypass rather than a solution and essentially you end up with alot of unnecessary code.
I prefer to do things on the server side where the user has no idea of whats going on.
0
 
LVL 20

Expert Comment

by:steelseth12
Comment Utility
>> Don't know yet, working on the first idea still, it's easy to assign the PK of the coin as a value for the checkbox not sure yet how to use it on the receiving end.

if(in_array(PK,$_POST["slabed")) { // PK you must send with the form .... if PK exist in the slabed array then it is slabed

Its 5 AM over here i going to bed. Should be up in 3-4 hours let me know if you need anything else.
0
 
LVL 21

Assisted Solution

by:nizsmo
nizsmo earned 250 total points
Comment Utility
gamebits:

this is another way using javascript, will check the checkboxes for them but set the checkbox to 0 before doing so, so when the form is submitted the checkboxes will actually check it self.

In your php file then, you can check to see if the checkbox value (member[]) is a 0 or a 1.

I hope you understand what I am doing here, but it is far from elegant, though it should work.
<script language="javascript" type="text/javascript">

function checkForm()

{

	var myformR = document.myform.getElementsByTagName('input');

	for(i=1;i<myformR.length;i=i+2)

	{

		if(!myformR[i].checked)

		{

			myformR[i].value = 0;

			myformR[i].checked = true;

		}

	}

	//alert(myformR[1].checked)

	document.myform.submit();

}

</script>
 

<form name="myform" action="filter.php">

<input type="text" name="username[]" value="Bob">

<input type="checkbox" name="member[]" value="1">

<br>

<input type="text" name="text[]" value="Mark">

<input type="checkbox" name="member[]" value="1">

<br>

<input type="text" name="text[]" value="Sophie">

<input type="checkbox" name="member[]" value="1">

<br>

<input type="button" value="Submit" onclick="checkForm();">

</form>

Open in new window

0
 
LVL 21

Expert Comment

by:nizsmo
Comment Utility
Sorry i forgot to mention though, my solution i posted above although works, is assumed (you can probably tell from the for loop) that there is one text box and then one checkbox, consecutively one after another. As long as the patter is like that, the script should work with no problems.

I know it is not elegant nor pretty, but at least its an idea that is sort of working.
0
 
LVL 28

Author Comment

by:gamebits
Comment Utility
Well since I don't have much time on hand and this seems to be more complicated than what I expected I will get the end result that I want thru the back door.

Since the user will check the box to flag it as slabed and will enter the company who slabed it I will do the insert setting the variable $slabed  = "0"; and right after the query I will run an update query

UPDATE `TBL_Member`
       SET `slabed` = '1'
  WHERE `slabed_by` != ''

This work for now, may be system intensive if the table get to be a couple million rows though.

Thanks both of you for your inputs I need more time to try them.
0
 
LVL 21

Expert Comment

by:nizsmo
Comment Utility
no worries gamebits. let me know after you have tried the javascript solution above and let me know if it works or not (should since i have tested it..)
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

763 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now