Link to home
Start Free TrialLog in
Avatar of oneoakgirl1
oneoakgirl1Flag for United States of America

asked on

Insert dynamic checkbox values into multiple mysql fields using php

I need to insert dynamically populated checkbox values into multiple fields of a mysql database using php. I think I need a "for each" statement, but can't seem to get it right.
Here's the php (while statement) that sets up the checkboxes - this works:

 // Show records by while loop.
while($rows=mysql_fetch_array($list)){
 ?>
<input name="nominee" type="checkbox" id="nominee[]" value="<?php echo $rows['n_uuid']; ?>">&nbsp;&nbsp;<?php echo $rows['n_first']; ?> <?php echo $rows['n_last']; ?> - <?php echo $rows['n_uuid']; ?><br />
<?php
// End while loop.
}
?>

Now - I'm stuck on my insert...
As I said - I need to insert all checked values into one row, separate fields in the database

This is for an election voting process for the staff senate. There are 8 clusters A,B,C,D, etc. involved with a total of about 300 voters.

The voters login and are authenticated through LDAP - then through a table with all voters names. If they aren't in that table - they can't vote.

Once authenticated, they are presented with this dynamically populated checkbox list with nominees from their cluster. Each cluster has a different amount of seats open for nomination so the checked boxes will be different amounts each time.

If I can just get them into separate fields of the database, I'll be happy.
Thanks for your help.
Debra
Avatar of hielo
hielo
Flag of Wallis and Futuna image

On the code you posted you are NOT generating unique ids for your checkboxes. The ids should be unique and the name should be nominee[] ( see attached code )

With that code, when you want to process the checkboxes the you would do:
$nominees = $_REQUEST['nominee'];//this will give you an array of the checked nominee checkboxes

foreach( $nominees as $k => $v)
{
 //do whatever you need with the values
 echo $v;
}
<?php
 // Show records by while loop.
while($rows=mysql_fetch_array($list)){
 ?>
<input name="nominee[]" type="checkbox" id="nominee<?=$rows['n_uuid']?>" value="<?php echo $rows['n_uuid']; ?>">  <?php echo $rows['n_first']; ?> <?php echo $rows['n_last']; ?> - <?php echo $rows['n_uuid']; ?><br />
<?php
// End while loop.
}
?>

Open in new window

What does the database look like?

You should be able to echo the checked values

foreach ($_POST['nominee'] as $key=>$value)
  echo "key: ". $key. " value: ". $value ."<br />\n";
Avatar of oneoakgirl1

ASKER

My database has 13 fields -
n_cluster, nominee1, nominee2, nominee3, nominee (4-12)

$n_cluster is a session variable defined in the login script

So would the following be correct? Do I have to name each field in the insert statement?

$query = "INSERT INTO nominee_results08 (n_cluster,nominee1, nominee2, nominee3, nominee4, nominee5, nominee6, nominee7, nominee8, nominee9, nominee10, nominee11, nominee12) values ('".$n_cluster."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."','".$_REQUEST['nominee']."'
)";
There are a possible amount of nominees up to 12 - so the DB fields are:
cluster, nominee1, nominee2,nominee3 (etc up to 12) (all varchar)

cluster is a session variable defined from the login

Do I have to name each field in the insert statement like this...

$query = "INSERT INTO nominee_results08 (n_cluster,nominee1, nominee2, nominee3, nominee4, nominee5, nominee6, nominee7, nominee8, nominee9, nominee10, nominee11, nominee12) values ('".$n_cluster."','".$_POST['nominee']."',,'".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee']."','".$_POST['nominee'].'",'".$_POST['nominee']."');
You don't see this as the same value over and over?
".$_POST['nominee']."',,'".$_POST['nominee']."','".$_POST['nominee']."

you could try

".$_POST['nominee'][0]."',,'".$_POST['nominee'][1]."','".$_POST['nominee'][2]."

Yes - I did see it that way, but was unclear on IF I could do the double bracket set like that... That's why I need an expert.
:)
I'll try it
That will not work. What does your html look like? The code that the browser sees/gets?
Oh and fix the double ,, in there.

That will fill the fields from nominee1, nominee2... ( up to the number of checked items) with the n_uuid value.
Here's the setup for the checkboxes - didn't think you'd need to see the connect code - it works and populates the checkboxes...
Thanks for any help you can give. Really on a timeline with this - the executive committee asked me to do this last week. Never did the multiple checkbox thing.. Attached is the code
<h4>The following list is populated from staff members in the <b>"<?php print ($n_cluster); ?>" Cluster</b> who have agreed to serve on the Staff Senate if elected.</h4>
<h4>There are <?php print ($seats); ?> open seats in your cluster. Please choose <?php print ($number_choices); ?> nominees from your cluster.</h4>
 
 
 
<form id="nominee" name="nominee" method="post" action="insert.php">
<input type="hidden" name="v_uuid" value="<?php print ($v_uuid); ?>"/>
<input type="hidden" name="n_cluster" value="<?php print ($n_cluster); ?>">
<input type="hidden" name="seats" value="<?php print ($seats); ?>">
<input type="hidden" name="number_choices" value="<?php print ($number_choices); ?>">
 
<?php
				
$list=mysql_query("select * from nominees where n_cluster = '".$n_cluster."' order by n_last asc");
//echo "select * from nominees where nominees.n_cluster = '".$n_cluster."' order by n_last asc" . "<br/>";
$result = mysql_query($list,$link); // or die("Checking for Voter - can't connect. ".mysql_error());//Check if uuid is valid
//echo $query . "<br/>";
$rows = mysql_fetch_row($result);
$n_last=$rows[0];
$n_first=$rows[1];
$n_uuid=$rows[2];                               
 
 
 // Show records by while loop.
while($rows=mysql_fetch_array($list)){
 ?>
<input name="nominees[]" type="checkbox" id="nominees<?=$rows['n_uuid']?>" value="<?php echo $rows['n_uuid']; ?>">  <?php echo $rows['n_first']; ?> <?php echo $rows['n_last']; ?> - <?php echo $rows['n_uuid']; ?><br />
<?php
// End while loop.
}
?>  <input type="submit" name="submit" value="Vote for Nominees">
</form>

Open in new window

btw

$rows = mysql_fetch_row($result);
$n_last=$rows[0];
$n_first=$rows[1];
$n_uuid=$rows[2];                              
 

if you use

$rows = mysql_fetch_assoc($result);

then you can reference fields like

echo $row['n_last'];

OH MY, I SEE CLEARLY NOW. You are attempting to reference that way.

Change your mysql_fetch_row to mysql_fetch_assoc and get rid of the next 3 lines.
 
This is my full insert.php file. I've changed the $rows = mysql_fetch_row($result); to $rows = mysql_fetch_assoc($result);

I'm searching the page for errors, because it's giving me a blank screen - not echoing anything...
<?php
session_start();
 
if (isset($_REQUEST['nominees'])) {
 
  $nominees=$_REQUEST['nominees'];
 
} else if (isset($_POST['nominees'])) {
 
  $nominees=$_POST['nominees'];
 
} else {
 
   $nominees=$_SESSION['nominees'];
 
}
 
 
if (isset($_REQUEST['v_uuid'])) {
 
  $v_uuid=$_REQUEST['v_uuid'];
 
} else if (isset($_POST['v_uuid'])) {
 
  $v_uuid=$_POST['v_uuid'];
 
} else {
 
   $v_uuid=$_SESSION['v_uuid'];
 
}
 
 
 
if (isset($_REQUEST['v_cluster'])) {
 
  $v_cluster=$_REQUEST['v_cluster'];
 
} else if (isset($_POST['v_cluster'])) {
 
  $v_cluster=$_POST['v_cluster'];
 
} else {
 
   $v_cluster=$_SESSION['v_cluster'];
 
}
 
 
 if (isset($_REQUEST['n_cluster'])) {
 
  $n_cluster=$_REQUEST['n_cluster'];
 
} else if (isset($_POST['n_cluster'])) {
 
  $n_cluster=$_POST['n_cluster'];
 
} else {
 
   $n_cluster=$_SESSION['n_cluster'];
 
}
 
 if (isset($_REQUEST['n_last'])) {
 
  $n_last=$_REQUEST['n_last'];
 
} else if (isset($_POST['n_last'])) {
 
  $n_last=$_POST['n_last'];
 
} else {
 
   $n_last=$_SESSION['n_last'];
 
}
 
 if (isset($_REQUEST['n_first'])) {
 
  $n_first=$_REQUEST['n_first'];
 
} else if (isset($_POST['n_first'])) {
 
  $n_first=$_POST['n_first'];
 
} else {
 
   $n_first=$_SESSION['n_first'];
 
}
 
 if (isset($_REQUEST['n_uuid'])) {
 
  $n_uuid=$_REQUEST['n_uuid'];
 
} else if (isset($_POST['n_uuid'])) {
 
  $n_uuid=$_POST['n_uuid'];
 
} else {
 
   $n_uuid=$_SESSION['n_uuid'];
 
}
 
 
 
$link = mysql_connect ("localhost", "root", "") or die("Cannot connect to the database".mysql_error());
 
		mysql_select_db('StaffSenateElection2008',$link) //Select database 
				or exit ();
 
 
$query = "INSERT INTO nominee_resultss08 (n_cluster,nominees1, nominees2, nominees3, nominees4, nominees5, nominees6, nominees7, nominees8, nominees9, nominees10, nominees11, nominees12) values ('".$n_cluster."','".$_REQUEST['nominees'][0]."','".$_REQUEST['nominees'][1]."','".$_REQUEST['nominees'][2]."','".$_REQUEST['nominees'][3]."','".$_REQUEST['nominees'][4]."','".$_REQUEST['nominees'][5]."','".$_REQUEST['nominees'][6]."','".$_REQUEST['nominees'][7]."','".$_REQUEST['nominees'][8]."','".$_REQUEST['nominees'][9]."','".$_REQUEST['nominees'][10]."','".$_REQUEST['nominees'][11]."'");
echo $query; 
 
$result = mysql_query($query,$link) or exit ("NO RESULT".mysql_error());
 
if($result)
					{
						echo "<center><h3>You have successfully submitted your nominees.</h3></center>"
							}
session_write_close();
	
	
?>

Open in new window

found some syntax errors after reviewing my error logs
INSERT INTO nominee_resultss08(n_cluster,nominees1, nominees2, nominees3, nominees4, nominees5, nominees6, nominees7, nominees8, nominees9, nominees10, nominees11, nominees12) values ('O','kwnklmnn','khightwr','gyoung2','','','','','','','','','')

I'm going to try not naming my fields and see if that works.
D
Not naming fields didn't work - Is there a way to increment the fields in the insert statement?
use something like this

$sql_command = "insert into ......";
$ok= mysql_query($sql_command);
 if (mysql_errno() or $debug)
   echo "line: ". __LINE__ ."<br />\n".$sql_command."<br />\n".mysql_errno().": ".mysql_error()."<br />\n";

if and error occurs it will echo info
(if you set debug=TRUE; it will always echo)

not recommended for production machines, but good for testing.
You've been a lot of help and I'm almost there...please don't leave me yet.
Trying to increment the fields like this...

   
    for($i =0; $i<=11; $i++)
    {
        if(isset($_POST['nominees'.$i]))
        {
            $nominees = ",".$i;
             
        }
    }
ASKER CERTIFIED SOLUTION
Avatar of Michael701
Michael701
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
Oh - it's so close - that helped - here's what my echo query is giving me after it completes the script...

, 'jpullis', 'pmthomas', 'mtraynom', '', '', '', '', '', '', '', '', ''INSERT INTO nominee_resultss08(n_cluster,, 'jpullis', 'pmthomas', 'mtraynom', '', '', '', '', '', '', '', '', '') values ('O','')NO RESULTYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'jpullis', 'pmthomas', 'mtraynom', '', '', '', '', '', '', '', '', '') values (' at line 1



so it's getting the values but it's doing some other crazy stuff, too... You're really helping me :)
looks like you didn't build the $query correctly.

echo it by itself to see what it looks like.
I can't figure this out. Now it won't even insert my choices. And it was working before. Here is the full insert page. The session variables are from the login.  

Any ideas? I have to get this project completed.

<?php
session_start();
 
if (isset($_REQUEST['nominees'])) {
 
  $nominees=$_REQUEST['nominees'];
 
} else if (isset($_POST['nominees'])) {
 
  $nominees=$_POST['nominees'];
 
} else {
 
   $nominees=$_SESSION['nominees'];
 
}
 
 
 
 if (isset($_REQUEST['n_cluster'])) {
 
  $n_cluster=$_REQUEST['n_cluster'];
 
} else if (isset($_POST['n_cluster'])) {
 
  $n_cluster=$_POST['n_cluster'];
 
} else {
 
   $n_cluster=$_SESSION['n_cluster'];
 
}
 
 
 
 
$link = mysql_connect ("localhost", "xxxx", "xxxxx") or die("Cannot connect to the database".mysql_error());
 
		mysql_select_db('xxxxx',$link) //Select database 
				or exit ();
 
$nominees='';
for($i =0; $i<=11; $i++)
{
    if(isset($_POST['nominees'][$i]))
        $nominees .= ", '".$_POST['nominees'][$i]."'";
    else
    $nominees .= ", ''";
}
 
 
$query = "INSERT INTO nominee_resultss08(n_cluster,nominees1, nominees2, nominees3, nominees4, nominees5, nominees6, nominees7, nominees8, nominees9, nominees10, nominees11, nominees12) values ('".$n_cluster."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."')";
 
 
 
echo $query; 
 
 
$result = mysql_query($query,$link) or exit ("NO RESULT".mysql_error());
 
if($result)
					
						echo "<center><h3>You have successfully submitted your nominees.</h3></center>";
							
session_write_close();
	
	
?>

Open in new window

where did you get the idea that this will work?

$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."','".$_POST['nominees'.$i]."'

thought it was changed to something like

$_POST['nominees'][0]."','".$_POST['nominees'][1]."','".$_POST['nominees'][2]."'


---------------------

and you're double using a variable name, what's all this about? isn't the info passed as a $_POST from the <form>

if (isset($_REQUEST['nominees'])) {
 
  $nominees=$_REQUEST['nominees'];
 
} else if (isset($_POST['nominees'])) {
 
  $nominees=$_POST['nominees'];
 
} else {
 
   $nominees=$_SESSION['nominees'];
 
}

I had changed it back to see if the increment would work without the double bracket. I got a reply that the double brackets wouldn't work. I thought I was talking to the same person. I'll check the name from now on because it's better to talk to the same person.

Anyway, I changed it back to the $_POST['nominees'][0]."','".$_POST['nominees'][1]."','".$_POST['nominees'][2]."' version and commented out the session variable at the top. That was from before the increment.

Any chance you'll be on later or tomorrow morning? I have to leave now, but will pull this up later tonight from home and then hit the ground running in the am. I really do appreciate all your help. I'm gonna figure this out with your help.
Debra
Thanks again Michael701for your help in my dilemna - After some tweaking of the online voting application, I was able to begin testing (today) and so far...no major errors.