Jump to content

Checkboxes - Capturing user input, creating an array, and preserving values via session variables


Go to solution Solved by Dathremar,

Recommended Posts

Hey guys,

 

I have a basic form that contains a number of checkboxes, all with the same name. See below...

<input type='checkbox' name='share_category[]' value='Car Accommodation'>Car Accommodation
<input type='checkbox' name='share_category[]' value='Employed only'>Employed only
<input type='checkbox' name='share_category[]' value='Prefer someone quiet'>Prefer someone quiet

These checkbox values are being pulled from the database. There's roughly 25 checkboxes.

 

That's all good.

 

On the following page, I'm using this piece of code to split up the array and write it to screen (to debug and make sure the correct values are being passed)

$checked = $_POST['share_category'];
	for($i=0; $i < count($checked); $i++){
    echo $checked[$i] . "<br/>";
	}

Which gives me .....

 

Car Accommodation
Employed only
Prefer someone quiet

 

...on the confirmation page.

 

I should note that this form is posting data to a confirmation page, so users can take a look at what they've entered, and "go back" if they need to an ammend their entry before publishing it to the database.

 

This is where my question comes in.

 

How can I show the correct checkboxes ticked when they go back?

 

Here's a single checkbox option that I have working using session variables. I'm ok with this. I understand how it works.

<input	type="checkbox"	name="share_hide" value="1" <? if(isset($_SESSION['share_hide'])) if($_SESSION['share_hide'] == 1 ) echo "checked"?>>

I just don't know how to "pull apart" the array to see which boxes they've checked.

 

I would assume it's an "instring" type function?

 

Oh, and lastly (my apologies) ...here is the code that creates the checkboxes.

<?
echo "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='body_text' style='padding-left:20px; padding-right:15px;'>";

$strSQL = mysql_query("SELECT * FROM tblcategories ORDER BY cat_ID ASC");

$boxes_per_row = 4;
					
for($x = 0; $r = mysql_fetch_array($strSQL); $x++){
if($x % $boxes_per_row == 0){
echo "<tr>";
}
	
$cat_category = $r["cat_category"];
echo "<td><input type='checkbox' name='share_category[]' value='$cat_category'>$cat_category<td>";
					
if ($x % $boxes_per_row == ($boxes_per_row)-1) {
echo "</tr>";
}
}

if($x != mysql_num_rows($strSQL)){
echo "</tr>";
}
					
echo "</table>";
					
?>
Edited by ramone_johnny
Link to comment
Share on other sites

You look like you know what youre doing so this should help, found this:

 

http://www.w3schools.com/tags/att_input_checked.asp

<form action="demo_form.asp">
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car
<br><input type="submit" value="Submit">
</form> 

Edit:

Sorry, totally read that wrong!, you already got this ^^^

Edited by Phear46
Link to comment
Share on other sites

Why are you using the cat_category for the value instead of the ID?

 

Anyway, give this a try

 

<?php

//Start with configuration variable
$boxes_per_row = 4;

//Set array of selected categories
$selectedCategories = isset($_POST['share_category']) ? $_POST['share_category'] : array();

//Then get the data you need
$query = "SELECT cat_ID, cat_category FROM tblcategories ORDER BY cat_ID ASC";
$result = mysql_query($query);

//Process the data into output
$rowCount = 0;
while($row = mysql_fetch_assoc($result))
{
    $rowCount++;
    if($rowCount % $boxes_per_row == 1)
    {
        echo "<tr>";
    }

    //Determine checked state
    $checked = (in_array($row['cat_ID'], $selectedCategories)) ? ' checked="checked"' : '';
    echo "<td><input type='checkbox' name='share_category[]' value='{$row['cat_ID']}'>{$row['cat_category']}{$checked}<td>";

    if($rowCount % $boxes_per_row == 0)
    {
        echo "</tr>";
    }
}

if($rowCount % $boxes_per_row != 0)
{
    echo "</tr>";
}

?>

<table width='100%' border='0' cellpadding='0' cellspacing='0' class='body_text' style='padding-left:20px; padding-right:15px;'>
<?php echo $checkBoxOutput; ?>
</table>
Link to comment
Share on other sites

Okay, getting closer.

 

The first issue is constructing the array.

 

I have this bit of code, but it's not appending anything after the first value?

$checked = $_POST['share_category'];
for($i=0; $i < count($checked); $i++){
$_SESSION['share_category'] = $checked[$i] . ", ";
}
echo $_SESSION['share_category']

Then I guess I'll need to do something like this on the other page.

$selectedCategories = isset($_SESSION['share_category']) ? $_SESSION['share_category'] : array();
Link to comment
Share on other sites

Okay, I *think* I'm getting closer with this.

 

Here's the session variable that contains the array.

$_SESSION['share_category'] = isset($_REQUEST["share_category"]) ? $_REQUEST["share_category"] : "";

And here's the code that I was helped with earlier.

<?
echo "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='body_text' style='padding-left:20px; padding-right:15px;'>";

$strSQL = mysql_query("SELECT * FROM tblcategories ORDER BY cat_ID ASC");

//Set array of selected categories
$selectedCategories = isset($_SESSION['share_category']) ? $_SESSION['share_category'] : array();

// [x] photos per row, change this to the number of photos/images you want per row
$images_per_row = 4;
					
for($x = 0; $r = mysql_fetch_array($strSQL); $x++){
if($x % $images_per_row == 0){
echo "<tr>";
}
	
//customize this to the variables you want to grab
$cat_category = $r["cat_category"];
$cat_ID = $r["cat_ID"];
	
//customize to display image
					
$checked = (in_array($r['cat_ID'], $selectedCategories)) ? ' checked="checked"' : '';
echo "<td><input type='checkbox' name='share_category[]' value='{$r['cat_ID']}'>{$r['cat_category']}{$checked}<td>";
			
//Here's the key part, this adds a new row after the [x]result/image from the database is echo'd
if ($x % $images_per_row == ($images_per_row)-1) {
echo "</tr>";
}
}

if($x != mysql_num_rows($strSQL)){
echo "</tr>";
}
					
echo "</table>";
					
?>

Line 330 is giving me an error....?

Warning: in_array() expects parameter 2 to be array, string given in C:\xampp\htdocs\advertise\placeanad.php on line 330

Which is this line....

$checked = (in_array($r['cat_ID'], $selectedCategories)) ? ' checked="checked"' : '';

Any thoughts?

Edited by ramone_johnny
Link to comment
Share on other sites

 

Ah, okay, I *think* have created the array correctly?

$share_category = implode(', ', $_POST['share_category']);

 

The $share_category variable that you are crating is a string and not an array. Dont implode it (which creates the string), just use it as an array. Add all of the checked values to an array with:

 

array_push($array_name, $value);

 

which is the same as:

 

$array_name[] = $value;

 

And then the condition with in_array will work, since the second param should be the array to search in.

Link to comment
Share on other sites

You're right.

 

I realised that issue when I started getting "string" related errors.

 

Ive taken that out.

 

I now have...

$_SESSION['share_category'] = isset($_REQUEST["share_category"]) ? $_REQUEST["share_category"] : "";

...where do I use this?

$array_name[] = $value;
Link to comment
Share on other sites

Got it!

 

There was a slight issue with this bit of code which I changed up.

$checked = (in_array($r['cat_ID'], $selectedCategories)) ? ' checked' : '';
//echo "this is what checked equals : " . $checked;
echo "<td><input type='checkbox' name='share_category[]' {$checked} value='{$r['cat_ID']}'>{$r['cat_category']}<td>";

Creating the array like so.

$_SESSION['share_category'] = isset($_REQUEST["share_category"]) ? $_REQUEST["share_category"] : "";

Any issues you guys can see with this?

Link to comment
Share on other sites

Hey guys, I just wanted to follow up on this with one more question.

 

It seems this code falls over if $_SESSION['share_category'] is not set, as the following variable gets its value from it.

$selectedCategories = isset($_SESSION['share_category']) ? $_SESSION['share_category'] : array();

Here's the code in it's entirety.

 

Could someone chime in with how to prevent this from falling over if $_SESSION['share_category'] is not set?

 

Thanks.

<?
					echo "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='body_text' style='padding-left:20px; padding-right:15px;'>";

					$strSQL = mysql_query("SELECT * FROM tblcategories ORDER BY cat_ID ASC");

					//Set array of selected categories
					$selectedCategories = isset($_SESSION['share_category']) ? $_SESSION['share_category'] : array();
										
					// [x] photos per row, change this to the number of photos/images you want per row
					$images_per_row = 4;
					
					for($x = 0; $r = mysql_fetch_array($strSQL); $x++){
					if($x % $images_per_row == 0){
					echo "<tr>";
					}
	
					//customize this to the variables you want to grab
					$cat_category = $r["cat_category"];
					$cat_ID = $r["cat_ID"];
	
					//customize to display image
					$checked = (in_array($r['cat_ID'], $selectedCategories)) ? ' checked' : '';
					//echo "this is what checked equals : " . $checked;
    				echo "<td><input type='checkbox' name='share_category[]' {$checked} value='{$r['cat_ID']}'>{$r['cat_category']}<td>";
					
					//Here's the key part, this adds a new row after the [x]result/image from the database is echo'd
					if ($x % $images_per_row == ($images_per_row)-1) {
						echo "</tr>";
					}
					}

					if($x != mysql_num_rows($strSQL)){
						echo "</tr>";
					}
					
					echo "</table>";
					
					?>
Link to comment
Share on other sites

The error is ....

Warning: in_array() expects parameter 2 to be array, string given in C:\xampp\htdocs\advertise\placeanad.php on line 336

Which is...

$checked = (in_array($r['cat_ID'], $selectedCategories)) ? ' checked' : '';

Because $_SESSION['share_category'] has no value.

Link to comment
Share on other sites

  • Solution

I see. $_SESSION['share_category'] is set, but it is empty (has not value). Change your if condition to:

$selectedCategories = (isset($_SESSION['share_category']) AND !empty($_SESSION['share_category'])) ? $_SESSION['share_category'] : array();
Edited by Dathremar
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.