Populating checkboxes using php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

pyoungson
Forum Newbie
Posts: 18
Joined: Thu Aug 09, 2007 5:35 am

Populating checkboxes using php

Post by pyoungson »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hi, I had a form with 200 checkboxes (a lot I'm sure you'll agree) the values of which were the same as the names in a mysql database.  I have two problems: the first is that where ever a spelling mistake occurred the particular input would be ignored because it didn't match up with the database, the second problem is that the number of records in the database has now been upped to 1000.  I don't really want to have to write out 800 lines of a form.

I came up with the following php to try to get the rows from the mysql database and display them as checkboxes - a much simpler solution, I'm sure you'll agree.

Code: Select all

<?php

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

mysql_select_db("solvents", $con);

$sql = "SELECT * FROM solvents ORDER BY Name";  
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {
$Name = $row["Name"]; 


echo "<form name="myform" action="process1.php" method="POST">
<input type=checkbox name=Solvents[] value=$Name>"; 

}

?>
This falls over at form action= on line 19. I have tried to stick as close to the original html form as possible which i have shown below:

Code: Select all

<body>
  <form name="myform" action="process1.php" method="POST">
    <input type="hidden" name="check_submit" value="1" />
   
    <br />
    Choose the solvents:<br />
<input type="checkbox" name="Solvents[]" value="water" checked="checked" /> Water<br />
.
.
.
<input type="checkbox" name="Solvents[]" value="dipropylene glycol" /> Dipropylene glycol<br />




    <br /><br />

    <input type="submit" />
  </form>
</body>
I can't understand what is wrong with the first code - I hope that someone else may be able to help.

Thank you.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Put this at the top of your script

Code: Select all

ini_set('display_errors', true);
error_reporting(E_ALL | E_STRICT);
and check that the mysql_select_db() and mysql_query() calls are successful.

Oh and you have a parse error here:

Code: Select all

echo "<form name="myform" action="process1.php" method="POST">
<input type=checkbox name=Solvents[] value=$Name>";
Using double quotes inside double quoted string. I'd use a single quoted string.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

When outputting html with double quotes you need to use one of the following:

Code: Select all

echo "<input type=\"text\" name=\"myname\" value=\"{$myvalue}\" />\n";

// or 

echo '<input type="text" name="myname" value="'.$myvalue.'" />'."\n";

// or finally
echo <<<EOMYTEXT
    <input type="text" name="myname" value="{$myvalue}" />

EOMYTEXT;
Where I have used {$myvalue} the squigglies indicate variable usage. Not necessary for normal variables but if needing an array or object such as $myarray['1'] or $this->myvalue you need them. I tend to stick them in anyway.

When using single quotes you have to concatenate variables and also special characters like \n (which is a return) and cannot be included unless in a double quote.

For more information read up on Strings - php manual.

You may also want to check w3schools html page on forms to understand the differnce between radio buttons and check boxes. You do not need the name to be an array "Solvents[]". Solvent will automatically create an array for you. I also use a standard of always using all lowercase names but that is a personal preference.

Rather than being based on text I normally use numeric variable values for things like this. It gets around any spelling issues and also allows for the possibility of translation especially if the values relate to a database anyway.

As a final thing rather than a 1000 checkboxes why not have 2 lists with buttons Add>> and <<Remove. One list contains all possible options, the other the options which have been chosen (You could do it so if the item moved rather than duplicated). It may need a bit more work but would probably be more user friendly.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Just remembered one of your previous posts... Simple add column

If you remembered I stated the following...
CoderGoblin wrote:I would have to also question the basic database design if you are having to add columns using php. Normally you would have another table storing Red,Yellow, whatever with possibly a joining table sovent2colour. (Without seeing exactly what you are trying to do this is difficult to judge).
Why not use the following (taking a guess at the requirement):

Table products has table prod_id,prod_name,prod_desc
Table solvents has solvent_id,solv_name
Table product2solvent has prod_id, solvent_id

You can link in which product has which solvent using the product2solvent table. For all your checkboxes you get all values from the solvents table. As you have an id for each you can use integer values. You never have to add additional columns to tables and the whole thing should run faster when performing selections.

I know it can be frustrating changing things like this, but the earlier you do it the easier your life will be in the long run.

Edit: Even more complicated example...

Table products has table prod_id,prod_type,prod_name,prod_desc
Table solvents has solvent_id,solv_name
Table product2solvent has prod_id, solvent_id
Table producttypes has ptyp_id,ptype_name
Table ptype2solvent ptyp_id,solvent_id

This allows you to select common types of "product type" and have a set of solvents used for those products. As you can see the approach is very flexible.
Last edited by CoderGoblin on Wed Aug 22, 2007 6:04 am, edited 1 time in total.
pyoungson
Forum Newbie
Posts: 18
Joined: Thu Aug 09, 2007 5:35 am

Post by pyoungson »

Thank you for that. The correction you proposed at least gets me some of the way there. The while loop is working now as I get the result 1000 times, however there is no writing just checkboxes. If you can imagine 1000 checkboxes one after the other (I know I need a break return but I don't think that is the crux of the problem) then that is what the script returns.

More about the table structure: The table consists of five columns but only the first one is of relevance to this (it is called Name). I thought the obvious thing to do would be to add $Name after the input but this just results in 1000 instances of a checkbox followed by $Name.

This is the code so far:

Code: Select all

<?php

ini_set('display_errors', true);
error_reporting(E_ALL | E_STRICT);

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

mysql_select_db("solvents", $con);

$sql = "SELECT * FROM solvents ORDER BY Name";  
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {
$Name = $row["Name"]; 


echo '<form action="process1.php" method="POST">
<input type=checkbox name=Solvents[] value=$Name>"$Name"'; 

}

?>
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

You are outputting the "<form" 1000 times. Take it out the loop and ensure you close it.

Code: Select all

<?php

ini_set('display_errors', true);
error_reporting(E_ALL | E_STRICT);

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

mysql_select_db("solvents", $con);

$sql = "SELECT * FROM solvents ORDER BY Name"; 
$result = mysql_query($sql);

echo '<form action="process1.php" method="POST">';
while ($row = mysql_fetch_assoc($result)) {
  $Name = $row['Name'];
  echo '<input type="checkbox" name="Solvents[]" value="$Name">'.$Name.'<br />';
}
echo '</form>';

?>
You were not concatenating properly either. Also changed a couple of other bits including changing mysql_fetch_array to mysql_fetch_assoc

It will appear I'm being a nag :twisted: but try not to use root as the database user - create a new database user and password to use. After initial installation the root password should never be left empty. It's often a good idea when posting to replace the username and password in code examples with ****.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Solvents[] is not valid as a name if used more than once. A name must be unique. Use a for loop to put an index value in:

Code: Select all

for ($i = 0; $row = mysql_fetch_assoc($result); ++$i) {
    $name = 'Solvent[' . $i . ']';
}
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

ids must be unique, not names.
pyoungson
Forum Newbie
Posts: 18
Joined: Thu Aug 09, 2007 5:35 am

Post by pyoungson »

Thank you, that works great.

The only problem now is that it doesn't send the same array to the process1.php file.

The process1.php file is expecting $_POST['Solvents'], I'm not sure what is being sent this time (Is there a way I can check this), however the output from process1.php shows that the POST variable was not received correctly all I receive is zeros.

Is it still $_POST['Solvents'] that I am trying to receive or is it something else? I tried changing Solvents[] to Solvents as you suggested above but had no luck.

Thank you again for the time you have put into this.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

When you get problems like this (either with $_GET or $_POST values) the easiest solution is to use var_dump or print_r at the top of your script.

Code: Select all

print_r($_POST);
You can then check this against what you are expecting.

As another point... Is the example code part of process1.php ?

If not, the normal method of doing things is

Code: Select all

<?php
   if (!empty($_POST['checkform'])) {
       // Validate entries and set something like $valid=1 or an error message
       if ($valid) {
         header('Location: http://mysite.com/nextpage.php');
         exit;
       }
   }
   // Get what you need for output
   // Output
?>
OK very simplistic but I hope you can understand it. If you need more explanation including why people normally do it this way, let me know. If the original example code is already in process1.php you could remove 'action="process1.php"' from your form output. Then, if you ever change the name of the file you will not have to change the code.
pyoungson
Forum Newbie
Posts: 18
Joined: Thu Aug 09, 2007 5:35 am

Post by pyoungson »

The first page is the example I have given process1.php has the following code - Only the first few lines are here:

Code: Select all

print_r($_POST);

if (array_key_exists('check_submit', $_POST)) {
   
   if ( isset($_POST['Solvents']) ) { 
     $_POST['Solvents'] = implode('\', \'', $_POST['Solvents']); 
   }

} else {
    echo "You can't see this page without submitting the form.";
}

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

mysql_select_db("solvents", $con);

$result = mysql_query("SELECT * FROM solvents WHERE Name 

IN('{$_POST['Solvents']}')");



$dispersive = mysql_query("select name, dispersive as max_dispersive
from solvents
where name in('{$_POST['Solvents']}')
and dispersive = ( select max(dispersive)
                          from solvents
                          where name in('{$_POST['Solvents']}')
                        )");

while($row = mysql_fetch_array($dispersive))
{
$maxdispersive = $row['max_dispersive'];
}
So I've been processing the data from the form by imploding the array and finding the maximum value which is associated with the previously selected solvents. The mysql table has a second column named dispersive.

Now, with the print command I get the following on screen when the form is submitted and process1.php is run:
Array ( [Solvents] => Array ( [0] => $Name [1] => $Name [2] => $Name [3] => $Name ) ) You can't see this page without submitting the form.
Notice: Undefined variable: maxdispersive in C:\Program Files\EasyPHP 2.0b1\www\solventcalculator\process1.php on line 112
As you can see, process1.php is not picking up the names of the solvents correctly and is therefore not finding the data in the mysql table. I am happy to do it by numbers if this is easier but would prefer it to be by name.

Thank you once again.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Code: Select all

echo '<input type="checkbox" name="Solvents" value="$Name">'.$Name.'<br />';
should be

Code: Select all

echo '<input type="checkbox" name="Solvents" value="'.$Name.'">'.$Name.'<br />';
Should have noticed previously. :oops:
pyoungson
Forum Newbie
Posts: 18
Joined: Thu Aug 09, 2007 5:35 am

Post by pyoungson »

I am still having problems with this.

The problem is that the form is only returning the bottom-most checked check-box. i.e. if I check four check-boxes then only one is sent on to the processing php.

This is the form code:

Code: Select all

<html>
<head>
  <title>Solvent Calculations</title>
</head>
<body>
<?php


ini_set('display_errors', true);
error_reporting(E_ALL | E_STRICT);

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

mysql_select_db("solvents", $con);

$sql = "SELECT * FROM solvents ORDER BY Name";
$result = mysql_query($sql);

echo '<form action="process1.php" method="POST">';
while ($row = mysql_fetch_assoc($result)) {
  $Name = $row['Name'];
  echo '<input type="checkbox" name="Solvents" value="'.$Name.'">'.$Name.'<br />';
}
echo '<input type="submit" />';
echo '</form>';

?>
 
</body>
</head>
</html>
This then passes to the process php where calculations are performed on the data:

Code: Select all

<?php

print_r($_POST);

if (array_key_exists('check_submit', $_POST)) {
   
   if ( isset($_POST['Solvents']) ) { 
     $_POST['Solvents'] = implode('\', \'', $_POST['Solvents']); 
   }

} else {
    echo "You can't see this page without submitting the form.";
}

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

mysql_select_db("solvents", $con);

$result = mysql_query("SELECT * FROM solvents WHERE Name IN('{$_POST['Solvents']}')");



$dispersive = mysql_query("select name, dispersive as max_dispersive
from solvents
where name in('{$_POST['Solvents']}')
and dispersive = ( select max(dispersive)
                          from solvents
                          where name in('{$_POST['Solvents']}')
                        )");

while($row = mysql_fetch_array($dispersive))
{
$maxdispersive = $row['max_dispersive'];
}
As you can see the code is attempting to get the maximum value from an array. This is the output that I get when I choose four checkboxes at random on the input form:
Array ( [Solvents] => Water ) You can't see this page without submitting the form.
It is clear that the code is only returning the checkbox with the value "water" and not the three other checkboxes that had been checked.

I think it is the imploding of the array which used to work when I had a simple html form but now I have php in the form things have changed.

Anyone have any ideas?
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

What happens if you change the form checkbox echo to

Code: Select all

echo '<input type="checkbox" name="Solvents['.$Name.']" value="'.$Name.'">'.$Name.'<br />';
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Or even

Code: Select all

echo '<input type="checkbox" name="Solvents[]" value="'.$Name.'">'.$Name.'<br />';
Post Reply