# Form Check boxes saving info into php session



## throdne (May 14, 2006)

Hello, I'm newish to web development and I have a question about saving the info from checkboxes into a php session

here is what i have as a demo


```
<?php
session_name('job');
// Starting the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
.
.
.

$mysqlProblem = mysql_query("SELECT * FROM problem");
echo('');
while($problemRow = mysql_fetch_array($mysqlProblem))
	{
		echo("" . $problemRow['problemDescription'] . "
");
	}

echo('');
echo('');
. 
.
.
.

if($_POST['problemForm']=='1')
{
	$_SESSION['job'] = 11;
}
elseif($_POST['problemForm']=='5')
{
	$_SESSION['job'] = 55;
}
elseif($_POST['problemForm']=='2')
{
	$_SESSION['job'] = 22;
}

 echo($_SESSION['job']);

?>
```
all this info isn't on one page. i just cut here and there.

what's happening is that it's not writing the value of the checkbox to the session when hit submit.

o it does pull the info from the mysql correctly in line.

```
echo("<input type='checkbox' name='problemForm' value='" . $problemRow['problemID'] . "' />" . $problemRow['problemDescription'] . "<br />");
```
so if someone can help me out that will be great.
Throdne


----------



## andythepandy (Jul 2, 2006)

Hi throdne, I can see a few things that may the problem.

In your while loop, you are creating a new form element for every 'problem' there is, and then you are just ending one of them, I think you'll want:


```
echo('');
while($problemRow = mysql_fetch_array($mysqlProblem))
	{
		echo("" . $problemRow['problemDescription'] . "
");
	}
```
The next thing is that all your checkboxes have the same name. Do you only one to be selected at once? If you do, you should use radio buttons because you can give them the same name, and then only one will ever be selected:


```
echo("" .
```
Andy


----------



## throdne (May 14, 2006)

ah! I don't know why I didn't see the echo(''); inside my while. Thanks for that one.

about the checkboxes, this is the order it should go;

1. pull the info from the mysql and puts it into the checkboes form
2. echo the checkboxes until there is no more rows in the problem table
3. . . . 
my table looks like this


```
problemID        problemDesciption           problemJobCode
     1          My internet isn't working       105,103,302
     2          Computer doesn't turn on        102,101
     5          this is a test.                 305
. . . . 
. . . .
```
So, when you look at the rendered page they will see three checkboxes. So lets say they want to check problems 1 and 5 ( I didn't do "3" because I wanted to make sure that it is saving other numbers then 1,2,3,)

I want it to save the values of the problemID, that way, down the road I can pull up the fix information with the problemJobCode.

I don't know if that helps any, but if you need more info please ask.

O, and you asked about the checkboxes' name, did I do something wrong. What is the difference between name="" and value="" ?
Throdne


----------



## ehymel (Aug 12, 2007)

I think the trouble you have is that you need to capture both the problemID and the problemJobCode. You can either build this logic into your processing later (if jobcode==305 then problemid=5) kind of thing, or capture both up front by coding your form correctly. The latter approach is more flexible, and after you get that working I would recommend separating even more the close dependence on mysql data specifics from form building.

Try something like this:


```
echo('');
while($problemRow = mysql_fetch_array($mysqlProblem)) {
    echo("" . $problemRow['problemDescription'] . "
");
}
```
Then process the form submission one ID at a time:


```
foreach ($_POST as $id=>$jobCode) {
    if ( $id == "problemForm1" ) {
        $_SESSION['job1'] = $jobCode;
    }
    if ( $id == "problemForm2" ) {
        $_SESSION['job2'] = $jobCode;
    }
    if ( $id == "problemForm5" ) {
        $_SESSION['job5'] = $jobCode;
    }
}
```
This is just a step in the right direction since the last part is hack coding. You should be able to generalize the 'if ($id==problemForm1) lines to not be so dependent on 1, 2, 5, etc., which is data from your database. That would eliminate the need to change your code everytime your database changed, and make the code LOTS more reusable.

What I wrote also starts creating multiple session variables, and what you want is probably better suited for an array, but that's another story!


----------



## throdne (May 14, 2006)

Hey man, thank for you reply.

what I plan on doing is writing my code so if I do change/add something in the database the code will automatically adapt to it. that is why i'm using the while loop and others.

I see what you are saying about capture both upfront. what i plan on doing is capturing the problemID(s) for now then later on making an array with it.

so if they checked boxes with the problemID 1 and 5, it will save that into the session. Then later when I call it back up. I'll have a function that will write an array.

so, something like this.


```
$jobCodeArray = mysql_query("SELECT problemJobCode FROM problem WHERE problemID='" . $_SESSION['job'] . "'");
```
something like that. I know that may not work but the logic is somewhat there.


```
echo("" . $problemRow['problemDescription'] . "
");

//shouldn't be like this?

 echo("" . $problemRow['problemDescription'] . "
");
```
any thanks again for your reply every bit helps.

Throdne


----------



## ehymel (Aug 12, 2007)

oops, my bad on the coding... that's what I get for multi-tasking.

Your logic seems fine (as long as you're within the same session of course!!).


----------



## throdne (May 14, 2006)

Do you know what is the difference between name="" and value="" ? andythepandy said something about it might be the wrong name. can you help be debug that.

Thanks
Throdne

P.S. I edited my code up top to match the changes I made.


----------



## ehymel (Aug 12, 2007)

The distinction between name and value is critical to understand how the form works. Andy didn't say you have the wrong name, but that you have the SAME name for every one. The explanation can be confusing since checkboxes (and radio buttons) of the same name are perfectly valid and exactly what you want within a group. But once you are asking 3 different questions you will need 3 different group names. I think once you have a good understanding of the difference between name and value you'll understand our code suggestions a lot more. Google can help a lot. Basically, name is just an identifier, while value represents the chosen option. That is true of any form element. Think of something like "what is your favorite color" with options 'red', 'green', 'yellow'. You could have a checkbox list with name "favorite_color", and when the user clicks 'red' and submits, then the form processing would look to the element with identifier (or name) 'favorite_color' and get the value (red). A separate question on the same page 'what is your favorite animal' with options 'dog', 'cat', 'fish' could have a name 'favorite_animal'. When the user clicks 'dog' and submits, then you process the form by looking at the element with name 'favorite_animal' to get the user's choice (or value) of 'dog'.

Hope this helps. It's really important and worthwhile to understand these fundamentals before diving into php form processing.


----------



## throdne (May 14, 2006)

Ok, I think I understand.

how should this be written to save my problemID into a session when hit submit?


```
echo("<input type='checkbox' name='problemForm' value='" . $problemRow['problemID'] . "' />" . $problemRow['problemDescription'] . "<br />");
```


----------



## ehymel (Aug 12, 2007)

throdne said:


> Ok, I think I understand.


I'll just take the opportunity to stress how important understanding these points to be able to process the forms like you are needing.



throdne said:


> ```
> echo("<input type='checkbox' name='problemForm' value='" . $problemRow['problemID'] . "' />" . $problemRow['problemDescription'] . "<br />");
> ```


You won't be able to extract the problemID from a form item like this. Use what I suggested (or at least the version you corrected) since that writes the problemID into the name of the checkbox being submitted. It might be helpful to you to use that php code and then study the code that gets generated in the client browser (View->Source).

You may have a perfectly good reason to use sessions for this, but are you sure this is what you want? Session variables are only good for that, the same session. If you go somewhere else or want to access the data later or from a different machine, the information is gone. Sessions are not the same as cookies. Storing the submitted form answers in a database would be even better.


----------



## throdne (May 14, 2006)

ehymel I want to thank you for all your help. You really don't know what this means to me.

Anyways, lets look at this a different way so i can understand the difference.

So, lets take a look at a static form without my PHP code so I can understand this better.


```
<form action="" method="post">
<input type="checkbox" name=" " value= " ">1<br />
<input type="checkbox" name=" " value= " ">2<br />
<input type="checkbox" name=" " value= " ">3<br />
<input type="checkbox" name=" " value= " ">4<br />
<input type="submit" name=" " value="Submit" />
</form>
```
Lets say some checked boxes 1 and 3 and hit submit. What info would go into each name=" " and value= " " for each checkbox? Also, the name=" " for the submit button. then after they hit submit I want to echo just "1" and "3". Can be written any way. "13" "1|3" "1,3" but I want to save that info into a session ($_SESSION['job']) then echo it from the session.

I see what you are saying about maybe saving it into the database. but I really didn't want to include users to get that info back. maybe far far down the road.



> It might be helpful to you to use that php code and then study the code that gets generated in the client browser (View->Source).


That's the way I work. lol. But, the problem is, I can't learn it if the code doesn't work in the first place. I think if you help me out with this last question, about the static form, I'll get it down to a science. i just need to see what you put into the name and value and also the PHP script to save it into a session.

Throdne


----------



## ehymel (Aug 12, 2007)

Great idea. Let's use your own data to get what you want. In fact, as I do this, perhaps I have misunderstood what you are wanting. I see now that what has thrown me off is you wanting to capture 2 pieces of information, either one of which can be discerned from your database table from the other. Since that's the case, it simplifies the problem quite a bit. The downside is that it's not flexible when you want to expand, but that's another topic.

Maybe this is all you need:

from your table:

```
problemID        problemDesciption           problemJobCode
     1          My internet isn't working       105,103,302
     2          Computer doesn't turn on        102,101
     5          this is a test.                 305
```
Your client would have this:

```
<form action="" method="post">
    <input type="checkbox" name="problemID" value= "1">My internet isn't working<br />
    <input type="checkbox" name="problemID" value= "2">Computer doesn't turn on<br />
    <input type="checkbox" name="problemID" value= "5">this is a test<br />
    <input type="submit" name="submit" value="Submit" />
</form>
```
Then to process your form back on the server:


```
if($_POST['problemID']=='1') {
    $_SESSION['job'] = 11;
} elseif($_POST['problemID']=='5') {
    $_SESSION['job'] = 55;
} elseif($_POST['problemID']=='2') {
    $_SESSION['job'] = 22;
}

 echo($_SESSION['job']);
```
This of course is looking remarkable like your original post. This could be cleaned up a lot with a switch...case block, or even better generalize it to your database with something like:


```
$id = $_POST['problemID'];
$mysqlJobCode = mysql_query( "SELECT problemJobCode FROM problem WHERE problemID = $id" );
$_SESSION['jobCode'] = $mysqlJobCode;
```
This approach eliminates the problem of needing to capture both the problemID and the problemJobCode all at once since they are already dependent on each other in your database.

Now that I've typed all this out, it's looking very much like your original question about why things aren't working. andy's suggestion was to use radio buttons instead of checkboxes if you only want to allow the user to be able to select one problem at once. If that's the case, change the input type from checkbox to radio in the above html and you're set.

The problem comes in when you process a checkbox in php, which sees checkboxes with the same name as an array, so you have to access the values of the checkboxes by looking at the array variable. That means the php processing code I wrote above (similar to your original question) will not work if you're wanting to let the users submit multiple options, and you also have to re-write the html to prepare the checkbox names for php processing. Try this combo instead:


```
<form action="" method="post">
    <input type="checkbox" name="problemID[]" value= "1">My internet isn't working<br />
    <input type="checkbox" name="problemID[]" value= "2">Computer doesn't turn on<br />
    <input type="checkbox" name="problemID[]" value= "5">this is a test<br />
    <input type="submit" name="submit" value="Submit" />
</form>
```
 and process with this:


```
if (isset($_POST['problemID'][1]) {
    if ($_POST['problemID'][1]=='1') {
        $_SESSION['job1'] = 11;
    } elseif($_POST['problemID'][1]=='5') {
        $_SESSION['job1'] = 55;
    } elseif($_POST['problemID'][1]=='2') {
        $_SESSION['job1'] = 22;
    }
}
// now repeat for the 2nd checkbox checked (if there is one):
if (isset($_POST['problemID'][2]) {
    if ($_POST['problemID'][2]=='1') {
        $_SESSION['job2'] = 11;
    } elseif($_POST['problemID'][2]=='5') {
        $_SESSION['job2'] = 55;
    } elseif($_POST['problemID'][1]=='2') {
        $_SESSION['job2'] = 22;
    }
}
// repeat for 3rd checkbox (and 4th, 5th, etc.)
```
Repeating all of this above code is silly and naturally belongs in a loop, and session variable names are quite rigid as well, so more compact code would be something like:


```
foreach ($_POST['problemID] as $key => $val) {
    $jobCode = mysql_query( "SELECT problemJobCode FROM problem WHERE problemID = $val" );
    $_SESSION['job'][$key] = $jobCode;
}

echo $_SESSION['job'][1] . '
';
echo $_SESSION['job'][2] . '
';
echo $_SESSION['job'][5] . '
';

//or more generically:
foreach ($_SESSION['job'] as $jobCode) {
    echo $jobCode . '
';
}
// or alternatively:
foreach ($_SESSION['job'] as $key => $jobCode) {
    echo 'job ' . $key . ' is ' . $jobCode . '
';
}
```
Hope this helps, it's a lot to absorb if you're new to php. I've not tested any of the code written above, just free-typed, so you may have to debug some.


----------



## throdne (May 14, 2006)

YES!!!!!!!! that is what i'm looking for! Thanks for everything. When I was reading and got to the part



> ```
> if (isset($_POST['problemID'][1]) {
> if ($_POST['problemID'][1]=='1') {
> $_SESSION['job1'] = 11;
> ...


I was like, wait can't a foreach solve that problem. Then BAM! there it was.

thanks again. I may have to rewrite some of the code. but that was a very very big help.

Throdne


----------



## ehymel (Aug 12, 2007)

Glad to help! Make sure to mark the thread solved if this works.


----------



## throdne (May 14, 2006)

Lame! everything works up until I get to the foreach part.


```
<?php
if (isset($_POST['problemForm'][2]))
	{ 
    if ($_POST['problemForm'][2]=='1') { 
        $_SESSION['job'] = 11; 
    } elseif($_POST['problemForm'][2]=='5') { 
        $_SESSION['job'] = 55; 
    } elseif($_POST['problemForm'][2]=='2') { 
        $_SESSION['job'] = 22; 
    } 
?>
```
works perfectly for when check box 2 is checked and it does echo 22

but when I use this it doesn't.


```
<?php
foreach ($_POST['problemForm'] as $key => $val) { 
    $jobCode = mysql_query( "SELECT problemJobCode FROM problem WHERE problemID='" . $val . "'" ); 
    $_SESSION['job'][$key] = $jobCode; 
}

echo $_SESSION['job'][1] . '
'; 
echo $_SESSION['job'][2] . '
'; 
echo $_SESSION['job'][5] . '
';

?>
```
I get an error if two or more things it checked. "Cannot use a scalar value as an array. . ." on line
$_SESSION['job'][$key] = $jobCode;

but if only one thing is checked i get "Invalid argument supplied for foreach()" on line 
foreach ($_POST['problemForm'] as $key => $val) {

I have also changed my forms to

```
<?php

$mysqlProblem = mysql_query("SELECT * FROM problem");
echo('');
while($problemRow = mysql_fetch_array($mysqlProblem))
	{
		echo("" . $problemRow['problemDescription'] . "
");
	}
echo('');
echo('');
?>
```
Throdne


----------



## ehymel (Aug 12, 2007)

Make sure that the $_POST variable you are checking matches the HTML input element name (one version during our conversation here named the checkboxes "problemID" while another version named them "problemForm". These have to match your "foreach($_POST[<<element name>>]..." processing.

Shouldn't affect anything, but you don't have to reference the $problemID in the element name during form generation with the way you are processing now. Notice the change in the echo line below:


```
<?php

$mysqlProblem = mysql_query("SELECT * FROM problem");
echo('');
while($problemRow = mysql_fetch_array($mysqlProblem))
    {
        echo("" . $problemRow['problemDescription'] . "
");
    }
echo('');
echo('');
?>
```
One other thing that can help a lot with tracking down problems during a debugging stage is liberal use of echo'ing or print'ing of variables. For example, I would start your processing script with "print_r($_POST);", and add "print_r($_POST['problemID']);" or "print_r($_POST['problemForm']);" to make sure you are seeing what you expect.


----------

