Jump to content

How do I format checkboxes to input them into MySQL database


VinceGledhill
 Share

Recommended Posts

Hi people.

 

I have a form which inputs into a database.

 

Here is the code that inserts a yes no option...

 <select name = "consent">
        <option value = "Yes" <?php if ($_POST['consent'] == 'Yes') { echo 'selected="selected"'; } ?>>Yes</option>
        <option value = "No" <?php if ($_POST['consent'] == 'No') { echo 'selected="selected"'; } ?>>No</option>
        
      
  </select>

 

However, I have been asked if I can make it a yes or no checkbox instead.

 

Please can you tell me how I need to code it so that the "yes" or "no" is recorded in the DB.

 

At the moment I just have this

 

<input name="consent" type="checkbox" value="Yes" />Yes<br />
    <input name="consent" type="checkbox" value="No" />No<br />

 

Thanks in advance

VinceG

Link to comment
Share on other sites

Something like this maybe of some help.. wrote it real quick and I've seen more optimized examples but I tend to code in a way that makes sense to me...

 

<?php 
if (isset ($_POST['consent']) && $_POST['consent'] =="Yes") {
$Y = "selected";
}
else if (isset ($_POST['consent']) && $_POST['consent'] =="No") {
$N ="selected";
}else {
$Y = "";
$N = "";
}
?>
<form name="form1" action="something.php" method="post">
<input type="checkbox" name="consent" value="Yes" <?php echo $Y;?> />
<input type="checkbox" name="consent" value="No" <?php echo $N;?> />
</form>

 

Then to record a Yes or No into the database is fairly simple.. on your processing page just grab the variable...

<?php
$consent = $_POST['consent'];
//$consent = Yes or No depending on the which button is checked.. we are looking at Name="consent" -> value="X" x is going to be Yes or No
?>

 

Hope that helps

Link to comment
Share on other sites

Thanks guys but what if I want multiple choices like this?

 <input name="Expertise" type="checkbox" value="Airframes" />Airframes<br />
    <input name="Expertise" type="checkbox" value="Engines" />Engines<br />
    <input name="Expertise" type="checkbox" value="Props" />Props<br />
    <input name="Expertise" type="checkbox" value="Electrics" />Electrics<br />
    <input name="Expertise" type="checkbox" value="Avionics" />Avionics<br />

Link to comment
Share on other sites

Thanks, how would my code look?  Sorry I'm so thick..

 

<?php
if (isset($_POST['Expertise']))
    foreach ($_POST['Expertise'] as $exp) {
        // do what you want with each selected experience
        echo $exp .'<br />';
    }
?>

<form method='post'>
    <input name="Expertise[]" type="checkbox" value="Airframes" />Airframes<br />
    <input name="Expertise[]" type="checkbox" value="Engines" />Engines<br />
    <input name="Expertise[]" type="checkbox" value="Props" />Props<br />
    <input name="Expertise[]" type="checkbox" value="Electrics" />Electrics<br />
    <input name="Expertise[]" type="checkbox" value="Avionics" />Avionics<br />
    <input type="submit" name="btnSubmit" value="Submit">
</form>

Link to comment
Share on other sites

Thanks for that mate, I've added it as you can see but it's not putting the info into the DB when I submit the form.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Stranded Flyer</title>
</head>

<body>

<?php

$host = 'localhost';
$usr = "user";
$password = 'password';
$db_name = 'stranded';

//connect to database
mysql_connect ("$host","$usr","$password") or die ('Error During Connect:<br>'.mysql_error());
mysql_select_db ("$db_name") or die ('Error Selecting DB:<br>'.mysql_error());

$surname = mysql_real_escape_string($_POST['surname']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$phone1 = mysql_real_escape_string($_POST['phone1']);
$phone2 = mysql_real_escape_string($_POST['phone2']);
$location = mysql_real_escape_string($_POST['location']);
$qualifications = mysql_real_escape_string($_POST['qualifications']); 
$expertise = mysql_real_escape_string($_POST['expertise']);
$assistance = mysql_real_escape_string($_POST['assistance']);
$languages = mysql_real_escape_string($_POST['languages']);
$e_mail = mysql_real_escape_string($_POST['e_mail']);
$consent = mysql_real_escape_string($_POST['consent']);
$published = mysql_real_escape_string($_POST['published']);
$comments = mysql_real_escape_string($_POST['comments']); 
$other_info = mysql_real_escape_string($_POST['other_info']);



$errorstring = ""; // default value of errorstring

function makeSafe($value)
{
    if (get_magic_quotes_gpc())
    {
        $value = stripslashes($value); 
    }
    
    $value = mysql_real_escape_string($value);
    
    return $value;
}

if(isset($_POST['submit'])) {
// Validate all the code inputs

// Captcha Validation


require_once('recaptchalib.php');
$privatekey = "etcetcetc";
$resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                             $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
   $errorstring = $errorstring. "Invalid CAPTCHA, please try again";
  } else {

if ($surname =="")
$errorstring = $errorstring. "Surname<br>";
if ($phone1 =="")
$errorstring = $errorstring. "phone1<br>";	
if ($phone2 =="")
$errorstring = $errorstring. "phone2<br>";
if ($location =="")
$errorstring = $errorstring. "location<br>";
if	($qualifications =="")
$errorstring = $errorstring. "qualifications<br>";
if ($assistance =="")
$errorstring = $errorstring. "assistance<br>";
if ($languages =="")
$errorstring = $errorstring. "languages<br>";
if ($e_mail =="")
$errorstring = $errorstring. "e_mail<br>";
if ($consent =="")
$errorstring = $errorstring. "consent<br>";
if ($published =="")
$errorstring = $errorstring. "published<br>";
if ($comments =="")
$errorstring = $errorstring. "comments<br>";	
if ($other_info =="")
$errorstring = $errorstring. "other info<br>";

// does the errorstring = "nothing"?

}
// Figure out which error message to show i.e. field validation or CAPTCHA
if ($errorstring !="")
   if (strstr($errorstring,"CAPTCHA")) echo $errorstring;
  else echo "You have not put anything in the following fields: <br><br> $errorstring";
//echo "If you have nothing to put in the box please type the word \"None\" or \"N\/A\"";
//die ("Please try again, ensuring that you fill out all the fields!");
else 
{


//echo "Your data has been saved";


$insert_query = "INSERT INTO HelperFormData (surname, firstname, phone1, phone2, location, qualifications, expertise, assistance, languages, e_mail, consent, published, comments, other_info) VALUES ('$surname', '$firstname', '$phone1','$phone2', '$location', '$qualifications', '$expertise', '$assistance', '$languages', '$e_mail', '$consent', '$published', '$comments', '$other_info')";
$insert_action = mysql_query($insert_query) or die ('Error During Insert :<br>'.mysql_error().'<br><br>Error occured running the following code :<br>'.$insert_query);

$id = mysql_insert_id();

echo "Thank you, Your details have been submitted.";
//include "resultcard.php";

// Output what the form looks like

// End of how the form looks 

}
}

if(!isset($_POST['submit']) || (isset($_POST['submit']) && !empty($errorstring)))
{
?>

<form name = "form1" method ="post" action="">
<table width="700" border="0" cellspacing="5" cellpadding="5" bgcolor = "#dddddd">
  <caption>
  Please complete: This will only take a few moments but please note the format required for Lat and Long otherwise your location will be mis-represented.  All fields are required.
  </caption>
  <tr>
    <td width = "50"> </td>
    <td width = "240"> </td>
    <td width = "250"> </td>
    <td width = "160"><b>Example Input</b></td>
  </tr>
  
  <tr>
    <td> </td>
    <td>Surname</td>
    <td><input type='text' name='surname' size = '40' maxlength='30' value = '<?php echo $surname; ?>'></td>
    <td>Smith</td>
  </tr>
  
  <tr>
    <td> </td>
    <td>First Name</td>
    <td><input type='text' name='firstname' size = '40' maxlength='30' value = '<?php echo $firstname; ?>'></td>
    <td>Bill</td>
  </tr>
  
  <tr>
    <td> </td>
    <td>Phone 1</td>
    <td><input type='text' name='phone1' size = '40' maxlength='30' value = '<?php echo $phone1; ?>'></td>
    <td>07777 777777</td>
  </tr>
  
  
  
  <tr>
    <td> </td>
    <td> </td>
    <td>The phone on which you are most likely to be reached</td>
    <td> </td>
    </tr>
  <tr>
    <td> </td>
    <td>Phone 2</td>
    <td><input type='text' name='phone2' size = '40' maxlength= '30'value = '<?php echo $phone2; ?>'></td>
    <td>0118 123 4567</td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
    <td>Alternative number if available, if you don't have one type "none"</td>
    <td> </td>
    </tr>
  <tr>
    <td> </td>
    <td>Location</td>
    <td><input type='text' name='location' size = '40' maxlength='40'value = '<?php echo $location; ?>'></td>
    <td>52.289071,-1.952004</td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
    <td colspan="2">IMPORTANT: Enter Enter LAT and LONG in DECIMAL DEGREES FORMAT WITH COMMA SEPARATOR (e.g. 51.341551,-1.936684) - it's easy to get this from a Google Map by RIGHT clicking on your location and then clicking on "WHAT'S HERE" - the LAT & LONG will appear in the search line above the map.</td>
    </tr>
  <tr>
    <td> </td>
    <td>Qualifications</td>
    <td><input type='text' name='qualifications'  size = '40' maxlength='30' value = '<?php echo $qualifications; ?>'></td>
    <td><p>LAA Inspector<br />
      Licenced Engineer<br />
      G.A. Pilot<br />
      Constructor<br />
      Microlight Pilot<br />
      Other
    </p></td>
  </tr>
  <tr>
    <td> </td>
    <td>Expertise</td>
    <td>
    <!--
    <input name="Expertise" type="checkbox" value="Airframes" />Airframes<br />
    <input name="Expertise" type="checkbox" value="Engines" />Engines<br />
    <input name="Expertise" type="checkbox" value="Props" />Props<br />
    <input name="Expertise" type="checkbox" value="Electrics" />Electrics<br />
    <input name="Expertise" type="checkbox" value="Avionics" />Avionics<br />
    <input type='text' name='expertise'  size = '40' maxlength='30' value = '<?php echo $expertise; ?>'> 
    -->
    
    <?php
if (isset($_POST['Expertise']))
    foreach ($_POST['Expertise'] as $exp) {
        // do what you want with each selected experience
        echo $exp .'<br />';
    }
?>


    <input name="Expertise[]" type="checkbox" value="Airframes" />Airframes<br />
    <input name="Expertise[]" type="checkbox" value="Engines" />Engines<br />
    <input name="Expertise[]" type="checkbox" value="Props" />Props<br />
    <input name="Expertise[]" type="checkbox" value="Electrics" />Electrics<br />
    <input name="Expertise[]" type="checkbox" value="Avionics" />Avionics<br />
    

    
    </td>
    
    <td><p>Airframes<br />
      Engines<br />
      Props<br />
      Electrics<br />
      Avionics<br />
      Other
    </p></td>
  </tr>
  <tr>
    <td> </td>
    <td>Assistance Offered</td>
    <td><input type='text' name='assistance' size = '40' maxlength='50' value = '<?php echo $assistance; ?>' /></td>
    <td><p>Air transport<br />
      Ground transport<br />
      Accommodation<br />
      Aircraft Parts<br />
      Engineering<br />
      Other:
    </p></td>
  </tr>
  <tr>
    <td> </td>
    <td>Language Skills</td>
    <td><input type='text' name='languages' size = '40' maxlength='50' value = '<?php echo $languages; ?>' /></td>
    <td><p>English / Spanish</p></td>
  </tr>
  <tr>
    <td> </td>
    <td>e_mail</td>
    <td><input type='text' name='e_mail' size = '40' maxlength='50' value = '<?php echo $e_mail; ?>' /></td>
    <td><p>example@mail.net</p></td>
  </tr>
  <tr>
    <td> </td>
    <td>Consent</td>
    <td>
      <select name = "consent">
        <option value = "Yes" <?php if ($_POST['consent'] == 'Yes') { echo 'selected="selected"'; } ?>>Yes</option>
        <option value = "No" <?php if ($_POST['consent'] == 'No') { echo 'selected="selected"'; } ?>>No</option>
        
      
  </select>
      
      </td>
    <td>Yes</td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
    <td colspan="2">By selecting YES I accept that the information I have provided will be displayed on an unlisted Google Maps page (Unlisted means: Shared only with other registered members who have been given the map's URL). I also agree not to use the information on this website for purposes other than for which it is intended and I will report any suspected misuse. Whilst Stranded Flyer endeavours to ensure that the information on this website is correct, we do not warrant its completeness or accuracy; nor do we commit to ensuring that the website remains available or that the material on the website is kept up-to-date.</td>
    </tr>
  <td><tr>
    <td> </td>
    <td>Published</td>
   
    
     <select name = "published">
     <option value = "Yes" <?php if ($_POST['published'] == 'Yes') { echo 'selected="selected"'; } ?>>Yes</option>
       <option value = "No" <?php if ($_POST['published'] == 'No') { echo 'selected="selected"'; } ?>>No</option>
</select>
    
   </td> 
   <td>Yes</td>
  </tr>
  <tr>
    <td> </td>
    <td>Comments</td>
    <td><textarea name= "comments" input type = 'text' rows = "5" cols = "29" /><?php echo $comments; ?></textarea></td>
    <td>As much info as possible 500 characters max</td>
  </tr>
  <tr>
    <td> </td>
    <td>Where did you hear about stranded flyer</td>
    <td><textarea name= "other_info" input="input" type = 'text' rows = "5" cols = "29" /><?php echo $other_info; ?></textarea></td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td><input type='submit' name='submit' value='Submit Your Info' /></td>
    <td colspan="2">
      <? require_once('recaptchalib.php');
  $publickey = "6LfVTtESAetcetc"; // you got this from the signup page
  echo recaptcha_get_html($publickey);
  ?></td>
  </tr>
</table>
</form>


</body>
</html>
<?php } ?>

Link to comment
Share on other sites

That's because it's an array of values and you are treating it as a single scalar value.

 

Ideally, having got the id of the new record added, the experience values would be written to a separate table with the new id and one experience in each record, as there is a one-to-many relationship

Link to comment
Share on other sites

this is my code to insert

$insert_query = "INSERT INTO HelperFormData (surname, firstname, phone1, phone2, location, qualifications, expertise, assistance, languages, e_mail, consent, published, comments, other_info) VALUES ('$surname', '$firstname', '$phone1','$phone2', '$location', '$qualifications', '$expertise', '$assistance', '$languages', '$e_mail', '$consent', '$published', '$comments', '$other_info')";

As far as I can see there is "expertise" there. 

 

Link to comment
Share on other sites

Copying and pasting the code into the location Barand has used in his example will not help you understand what's going on and is the reason for it not working.

 

You must understand what an array of values is and how to handle the sanitization of an array. I noted you have a "makeSafe" function and whilst sanitisation isn't overly important with checkboxes it is for other input types such as combo boxes.

 

That aside, you should read up on what an array is and how to handle them and then review the code given to you by Barand.

 

In short, an array is, as Barand said, an array of values. Each value has a unique key which identifies the value. When doing what Barand suggested:

 

 
<input name="Expertise" type="checkbox" value="Airframes" />Airframes<br />
<input name="Expertise" type="checkbox" value="Engines" />Engines<br />
<input name="Expertise" type="checkbox" value="Props" />Props<br />

 

The array created is :

 

$_POST['Expertise'][0] == 'Airframes';
$_POST['Expertise'][1] == 'Engines';
$_POST['Expertise'][2] == 'Props';

 

If you were to remove the 'value' attribute from the 'input' tags each Expertise array value would equal 'on' if the checkbox was ticked.

 

That touches on the basics of an array and how they are implemented with forms on the web but you still need to read and understand how to handle them. Your actually using a multi-dimensional array through the super global $_POST variable here so without realising it your using a more complex type of array.

Link to comment
Share on other sites

Without realising it I'm getting into deep water.

 

I don't really understand the PHP as you can obviously see. 

 

I have a form on my own site and have modified it here for a friend.  However, on my form I only have selections and not checkboxes.  I just wanted to know what code I needed to put in to make the "selections" from the checkboxes appear in the database.

 

As said above I was trying to help a friend out but it looks beyond me.  I'll have to let him know I'm of no use.

 

Thanks for all your input guys.

Link to comment
Share on other sites

This thread is more than a year old.

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.

 Share

×
×
  • 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.