• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 608
  • Last Modified:

Collect checkbox data in PHP/HTML/MySQL

I am setting up a form that gather different information. I need basic information, name, address, etc. which is done through text entry but then I need a bunch of information that is done by checkbox. What PHP owuld I use to get the  checkbox to record to the MySQL database if I have set the DB types to boolean (tinyint)? Here is what I am using for the text portions, LOA is the checkbox I can't get to work:

$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
if ((isset($_REQUEST['firstname'])) && (isset($_REQUEST['lastname'])) && (isset($_REQUEST['CWID'])) && (isset($_REQEUST['LOA'])))
if($result = mysql_query("INSERT INTO student (firstname, lastname, CWID) VALUES('$firstname', '$lastname', '$CWID') ") )
echo "Thank you, Your information has been entered into our database";
echo "ERROR: ".mysql_error();
  • 2
2 Solutions
First of all, LOA is not in the SQL code you've displayed above. Are you aware of that? If you are, can I see the HTML you are using?
Eddie ShipmanAll-around developerCommented:
Try this:
if ((isset($_REQUEST['firstname'])) && 
    (isset($_REQUEST['lastname']))  && 
    (isset($_REQUEST['CWID']))      && 
  $firstname = $_REQUEST['firstname'];
  $lastname  = $_REQUEST['lastname'];
  $CWID      = $_REQUEST['CWID'];
  $LOA       = $_REQUEST['LOA'];
  if ($result = mysql_query('INSERT INTO student (firstname, lastname, CWID, LOA) VALUES('.$firstname.', '.$lastname.', '.$CWID.', '.$LOA.')'))
    echo 'Thank you, Your information has been entered into our database.';
  } else {
    echo 'ERROR: '.mysql_error();

Open in new window

WARNING: checkboxes are only submitted if they are ticked.

<input type="checkbox" name="LOA" value="1">

you can always do the following to check for empty values..

<input type="hidden" name="LOA" value="0"/>
<input type="checkbox" name="LOA" value="1"/>

This will overwrite the hidden LOA value of 0, IF the checkbox is ticked.

In the processing part, predefine LOA as zero and only set it if a value has been given.
$LOA = 0;
if(isset($_REQUEST['LOA'])) $LOA = intval($_REQUEST['LOA']);  // see quotes below

ALSO enclose the textfields in quotes

  if ($result = mysql_query('INSERT INTO student (firstname, lastname, CWID, LOA) VALUES("'.$firstname.'", "'.$lastname.'", "'.$CWID.'", '.$LOA.')'))


make the values safe for a query by escaping any quotes included in the data using mysql_real_escape_string


Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now