Jump to content

Insert labels of checked checkboxes in database


Recommended Posts

I use the following code to generate a scrollable checkbox list of options:

 

<html>
<form action="SCRIPT.php">

<?php
	$expList = array('Engineering ','Science', 'Art', 'IT', 'Electronics', 'Communications');
        sort($expList);

                $tmp = array();
	$i = 1;
	$tmp[] = '<ul style="height: 95px; overflow: auto; width: 200px; border: 1px solid #480091; list-style-type: none; margin: 0; padding: 0;">';
	foreach ($expList as $option) {
     			$tmp[] = '<li id="li'  . $i . 'b"><label for="chk' . $i . 'b"><input name="chk' . $i . 'b" id="chk' . $i . 'b" type="checkbox" onchange="Enable(\'chk' . $i . 'b\',\'li' . $i . 'b\')">' . $option . '</label></li>';
     			$i++;
	}
	$tmp[] = '</ul>';
	echo implode("\n",$tmp) . "\n";
?>

<input type="submit">
</form>
</html>

But there are in fact over 50 options (not just 6) and they are in fact stored in an array $expList in an external php file called LISTS.php.

 

As you can see, the checkbox list consists of checkboxes chk1b, chk2b, chk3b, etc. with associated labels (Art, Communications, Electronics, etc.).

 

What I need in SCIPT.php is code that will insert each of the labels where the associated checkbox has been checked in my MySQL database. E.g. in this particular case: if chk1b & chk3b have been checked, 'Art' & 'Electronics' will be inserted. Also, I want the label of the first checked checkbox to be inserted in the (database) table column 'Exp1', the 2nd one in 'Exp2'.........25th one in 'Exp25' (I already have a script that allows a maximum of 25 checkboxes to be checked).

 

I'm guessing some sort of 'foreach' loop is required, but I can't quite work it out. Pls help!

 

Many thanks!

change chkbox name and add value attribute

$tmp[] = '<li id="li'  . $i . 'b"><label for="chk' . $i . 'b"><input name="chk_b[' . $i . ']" id="chk' . $i . 'b" type="checkbox" value ="'.$option.'"onchange="Enable(\'chk' . $i . 'b\',\'li' . $i . 'b\')">' . $option . '</label></li>';

and on submit page do

foreach $_POST['chk_b'] as $index => $option) echo $index, ' -> ', $option, '<br />\n';

Thanks for your help so far!

 

I've modified your code slightly to the following:

$i = 1;
foreach ($_POST['chk_b'] as $index => $option) 
{
echo $option, '<br>';
"$"."EXP".$i = '$option';
$i++;
}

 

Because I want to do the following:

1) print each option on-screen

2) assign $EXP1=first selected option, $EXP2=2nd selected option......... $EXP6=6th selected option, etc. (N.B. not neccesarily $EXP6=option with index 6)

 

1) is working

2) is not, can you see why? (it's probably a very elementary error, but I'm new to this stuff)

 

3) Also, the final thing I want to do is, once $EXP1, $EXP2, etc. have been assigned, to then insert $EXP1 in the MySQL table column #n, $EXP2 in column #n+1, $EXP3 in column #n+2, etc.

 

I'm familiar with how to connect to MySQL and insert data when all the variable names are known, but in this case I don't know how many 'EXP's the user will select and so, again, I'm guessing a foreach loop is required and I'm stuck...

 

Greatly appreciated if you could help me out!

Thanks.

<?php
$i = 1;
foreach ($_POST['chk_b'] as $index => $option) 
{
echo $option, '<br>';
        $fields[$i] = "`EXP$i`";
$value[$i] = "'$option'";
$i++;
}
//echo
$sql = "INSERT INTO table_name (". implode(', ', $fields). ") VALUES (". implode(', ', $value). ")";
?>

That's great! Thanks a lot!

 

Final question: 

 

The part where I connect to database & insert is actually in a different PHP script from the part where I generate $fields and $value, so I've tried to pass on $fields and $value as follows:

 

first script:

$i = 1;
foreach ($chk_b as $index => $option) 
{
   echo $option, '<br>';
        $EXPfields[$i] = "`EXP$i`";
   $EXPvalue[$i] = "'$option'";
   $i++;
}

print "
<html><body><form action='2ndscript.php' method='POST'>
<input type='hidden' name='EXPfields' value='{$EXPfields}'>
<input type='hidden' name='EXPvalue' value='{$EXPvalue}'>
</form></body></html>";

 

2nd script:

$EXPfields = $_POST['EXPfields'];
$EXPvalue = $_POST['EXPvalue'];

$link = mysql_connect  ('localhost', 'root');
if (!$link) {die('Could not connect: ' . mysql_error());}

$selectDB = mysql_select_db ('database_name', $link);
if (!$selectDB) {die('Could not select database: ' . mysql_error());}

$insert= mysql_query   ("INSERT INTO table_name (". implode(', ', $EXPfields). ") VALUES (". implode(', ', $EXPvalue). ")"); 
if (!$insert) {die('Could not insert into database: ' . mysql_error());}

 

However, I get the following error message:

Could not insert into database: Column count doesn't match value count at row 1

 

If I put the "connect to database & insert" part in the first script it works fine.

 

What have I done wrong? Is it not possible to pass on arrays like this? (So far I've only passed on single variables in this manner).

 

Thanks again.

Do you mean a way that does not require you to click a button to POST the values to the next page? If that's what you mean, I guess you could use header("location: nextpage.php?"); and append all values on the end of nextpage.php? thereby passing the values in the URL which is obviously undesirable.

 

FYI: POSTed information can be easily spoofed, much more easily than sessions. One of the first things I learned in PHP was to pass variables behind-the-scenes via sessions. Passing values via sessions takes fewer lines of code than what you've already got.

 

If you don't want to learn about sessions, then I would put all logic in the one file and then use header() to redirect to whatever page you need to go to after the logic is complete.

OK, so to clarify:

 

I now use the following code to generate a scrollable list of options: (call this SCRIPT1.php)

<html>

<form action="SCRIPT2.php" method=POST>

<?php
	$expList = array('Engineering','Science', 'Art', 'IT', 'Electronics', 'Communications');
        sort($expList);

                $tmp = array();
	$i = 1;
	$tmp[] = '<ul style="height: 95px; overflow: auto; width: 200px; border: 1px solid #480091; background-color:#E7E7E7; list-style-type: none; margin: 0; padding: 0;">';
	foreach ($expList as $option) 
            {
     			$tmp[] = '<li id="li'  . $i . 'b"><label for="chk' . $i . 'b"><input name="chk_b[' . $i . ']" id="chk' . $i . 'b" type="checkbox" value ="'.$option.'">' . $option . '</label></li>';
		$i++;	            
}
	$tmp[] = '</ul>';
	echo implode("\n",$tmp) . "\n";
?>

<input type="submit">
</form>
</body>
</html>

 

SCRIPT2.php then retrieves the selected options as follows:

<?php

$chk_b = $_POST['chk_b'];
$i = 1;
foreach ($chk_b as $index => $option) 
{
   echo $option, '<br>';
        $fields[$i] = "`EXP$i`";
   $value[$i] = "'$option'";
   $i++;
}
$EXPfields = implode(', ', $fields);
$EXPvalues = implode(', ', $value);
//echo $EXPfields;
//echo $EXPvalues;

print "
<html><body><form action='SCRIPT3.php' method='POST'>
<input type='hidden' name='EXPfields' value='{$EXPfields}'>
<input type='hidden' name='EXPvalues' value='{$EXPvalues}'>
<input type='submit''>
</form></body></html>
";

?>

 

SCRIPT3.php then retrieves $EXPfields and $EXPvalues as follows:

<?php

$EXPfields = $_POST['EXPfields']; 
$EXPvalues = $_POST['EXPvalues'];

//echo $EXPfields;
//echo $EXPvalues;

?>

 

So as you can see, SCRIPT1.php creates a scrollable list of options. SCRIPT2.php creates an array from all selected options ($value) and an array of column names where the selected options should eventually be inserted in the database ($fields).

 

Then SCRIPT2 creates a variable $EXPfields which is an implosion of $fields and a variable $EXPvalues which is an implosion of $value.

 

These 2 variables are then passed on to SCRIPT3.php via hidden form elements.

 

If I 'un-comment-out' "echo $EXPfields;" and "echo $EXPvalues;" in SCRIPT2.php the 2 imploded arrays are printed on-screen as expected. But if I do the same in SCRIPT3.php, only $EXPfields; is printed: it seems like $EXPvalues; isn't passed through properly.

 

So, hopefully that is slightly clearer now. Any ideas? Thanks!

 

I think I understand now. This is still far more trouble than sessions, especially if the user clicks the back button. but anyway...

 

You can't pass an array in a form field, per se. You will need to loop over the array values, setting each value in a hidden field.

 

$EXPfields = $_POST['EXPfields'];

foreach ($EXPfields AS $field_value) {
     echo "<input type='hidden' name='$EXPfields[]' value='$field_value'>";
}

 

... and then grab the array on the next page.

 

You should really just do

 

session_start();
$_SESSION['EXPfields'] = $_POST['EXPfields'];

 

and be done with it.

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.