Jump to content

Inserting checkbox values into mysql database


newphper

Recommended Posts

Hi,

 

I'm having more than enough trouble on this, hope somebody could shine some light on this for me!

 

I need to get the checked checkbox values into my database, all I'm getting though is either one checked value or the value Array??

 

Here is the necessary code below:

 

<?php
if (isset($_POST['Add Details'])) {
//taking the form data via POST and sticking into variables 
$facilities = $_POST['facilities'];

if (isset($_POST['facilities'])) { 
$facilities = $_POST['facilities']; 
}
foreach ($facilities as $value )

//Insert a row of informaiton into table "production"
  $query = "INSERT INTO production (facilities) VALUES ('$value')";

<input name="facilities[]" type="checkbox" id="facilities[]" value="rt" />

 

Thanks!

 

 

Link to comment
Share on other sites

What problems are you experiencing? The code above has problems, but nothing that would obviously make the code not function. Here are some things to address:

 

1. The values are not escaped before running in a query.

2. You are doing a query in a loop. You shoudl do just one query with all the valules

3. The code to insert the data should be inside the IF condition.

 

On second look, the problem may be that you are defining $facilities twice - once before the IF condition and once inside. If one fo the checkboxes are checked, then $facilities will be set as an empty value and the foreach will die. Plus, if the field "Add Details" is not passed inthe form, the code to insert the facilities values will not run.

 

if (isset($_POST['Add Details']))
{
    if (isset($_POST['facilities']) && is_array($_POST['facilities']))
    {
        $values = array();
        foreach ($facilities as $facility_value)
        {
            //Add escaped values to an array
            $values[] = "('" . mysql_real_escape_string($facility_value) . "')";
        }

        //Add ALL values to one query
        $query = "INSERT INTO production (facilities) VALUES " . implode(', ', $values);
        $result = mysql_query($query);
    }

    //Assume more code goes inside this IF condition
}

Link to comment
Share on other sites

Thank you for your help, it still just didn't work with my code for some reason, after working again for hours and hours I managed to put something together and yet again all I manage to get into my database is the word Array

 

this is UNBELIEVABLY FRUSTRATING!

 

Any help and input is VERY much appreciated!!

 

I would like to put this up here for anybody that may have the same problem too once I've completed.

 

<?php
if (isset($_POST['Add Details'])) {
//taking the form data via POST and sticking into variables 
$cartons = $_POST['cartons'];
$areaha = $_POST['areaha'];
$tonnage = $_POST['tonnage'];
$domestic_sales = $_POST['domestic_sales'];
$exports = $_POST['exports'];
$output_form = 'no';

if (empty($cartons)) {
      // We know at least one of the input fields is blank 
      echo 'Please fill out your carton information.<br />';
      $output_form = 'yes';
    }
  }
  else {
    $output_form = 'yes';
  }


  
  if (!empty($cartons)) {
// Connect to the database
  $dbc = mysqli_connect('hostname', 'username', 'password', 'databasename')  
or die('Error connecting to MySQL server.');

if(isset($_POST['facilities'])) 
{ 
 $_POST['facilities'] = implode(', ', $_POST['facilities']); //Converts an array into a single string
    }
$n = count($facilities);
$i = 0; 

} 

  //Insert a row of informaiton into table "production"
  $query = "INSERT INTO production (cartons, areaha, tonnage, domestic_sales, exports, facilities) VALUES ('$cartons', '$areaha', '$tonnage', '$domestic_sales', '$exports', '$facilities')";

mysqli_query($dbc, $query)
      or die ('Data not inserted.');

     echo 'Business added. <br /> <a href="form3.php">Next</a>';

    mysqli_close($dbc);

if ($output_form == 'yes') {

	}

?>

 

And my checkboxes look like this:

 

<input name="facilities[]" type="checkbox" value="restaurant" />
<input name="facilities[]" type="checkbox" value="winetasting" />
<input name="facilities[]" type="checkbox" value="cellartours" />

 

 

Link to comment
Share on other sites

Again, what problems are you seeing? Are you getting errors, a blank page, what???

 

Looking through the code above, there are some things where the logic is flawed:

 

1. You are using the variable $facilities in several places, but nowhere is it defined!

2. You are checking if $cartoons is empty, but the comments would suggest that any empty field should be an error.

3. You are using $output_form as a trigger (which is good), but you are not using it enough! You should use it to also determine if you should run the query

4. The query is run no matter what. It should be within an IF conditional to ensure there are values to insert and validation passes.

 

Here is a modification of your script based upon my assumptions. Note: Concatenating the 'facilities' values into a comma separated list is a bad process in my opinion. You shoudl save them as separate records associated with the parent record. But, I left it as is because I'm not interested in getting too involved in changing your database structure.

 

<?php

//Set default state for $show_form
$output_form = true;

//Form was posted
if (isset($_POST['Add Details']))
{
    //Validate input
    if (empty($_POST['cartons']) || empty($_POST['areaha']) || empty($_POST['tonnage']) ||
        empty($_POST['domestic_sales']) || empty($_POST['exports']) || count($_POST['facilities'])<1)
    {
        //Validation failed
	echo 'Please fill out your carton information.<br />';
	$output_form = 'yes';
}
    else
    {
        // Connect to the database
        $dbc = mysqli_connect('hostname', 'username', 'password', 'databasename')
               or die('Error connecting to MySQL server.');

        //escape the input 
        $cartons        = mysql_real_escape_string(trim($_POST['cartons']));
        $areaha         = mysql_real_escape_string(trim($_POST['areaha']));
        $tonnage        = mysql_real_escape_string(trim($_POST['tonnage']));
        $domestic_sales = mysql_real_escape_string(trim($_POST['domestic_sales']));
        $exports        = mysql_real_escape_string(trim($_POST['exports']));
	foreach($_POST['facilities'] as $key => $value)
        {
            $_POST['facilities'][$key] .= mysql_real_escape_string(trim($value));
        }
        $facilities = implode(', ', $_POST['facilities']);

	//Create and run the query
        $query = "INSERT INTO production (cartons, areaha, tonnage, domestic_sales, exports, facilities)
                  VALUES ('$cartons', '$areaha', '$tonnage', '$domestic_sales', '$exports', '$facilities')";
        mysqli_query($dbc, $query) or die ('Data not inserted.');
        mysqli_close($dbc);
}
}

if ($output_form) {
    //Include the form
}

?>

 

Link to comment
Share on other sites

Thank you so much for your help, I've been so preoccupied with the checkboxes I haven't really paid attention to anything else happening in my code. Will definitely these same points in mind in future.

 

I have applied your adjusted code to mine and the only problem I am experiencing at the moment is that after typing in the information on the form and clicking the submit button, the form will go blank and now nothing is written to the database..?

Link to comment
Share on other sites

And what debugging steps have you performed? You can't just write (or copy-paste) code and just "give up" when it doesn't work right. There are many simple steps you can take to identify the problem. Add some debugging code to the script to the code to echo out variable values, show when certain conditions are met, etc.

 

For eaxample, if you have an IF statement, put an echo right after the condition to display that the condition passed:

if (isset($_POST['Add Details'])){
    echo "'Add Details' POST value is set.";

 

In this particular case, the script I provided would not have any output if all the conditions and validations passed. Also, if you did not add the code for the form in the last condition or use an include() for the form, then nothing would be output. If you did not include the form code, then the validation might be failing. If the code for the form IS there, then your results make no sense. The only way to get a blank page would mean a record WAS inserted, but you say it isn't.

 

I've modified slightly to add some rudimentary debugging:

<?php

$debugMode = true;

function debug($msg)
{
    if ($debugMode)
    {
        echo "<div style=\"background-color:yellow;\">$msg</div><br />\n";
    }
    return;
}


//Set default state for $show_form
$output_form = true;

//Form was posted
if (isset($_POST['Add Details']))
{
    debug("Post value for 'Add Details' is set.");
    //Validate input
    if (empty($_POST['cartons']) || empty($_POST['areaha']) || empty($_POST['tonnage']) ||
        empty($_POST['domestic_sales']) || empty($_POST['exports']) || count($_POST['facilities'])<1)
    {
        debug("Validation failed. One of posted values is empty.");
        //Validation failed
	echo 'Please fill out your carton information.<br />';
	$output_form = 'yes';
}
    else
    {
        debug("Validation passed. None of the posted values are empty.");
        // Connect to the database
        $dbc = mysqli_connect('hostname', 'username', 'password', 'databasename')
               or die('Error connecting to MySQL server.');

        //escape the input 
        $cartons        = mysql_real_escape_string(trim($_POST['cartons']));
        $areaha         = mysql_real_escape_string(trim($_POST['areaha']));
        $tonnage        = mysql_real_escape_string(trim($_POST['tonnage']));
        $domestic_sales = mysql_real_escape_string(trim($_POST['domestic_sales']));
        $exports        = mysql_real_escape_string(trim($_POST['exports']));
	foreach($_POST['facilities'] as $key => $value)
        {
            $_POST['facilities'][$key] .= mysql_real_escape_string(trim($value));
        }
        $facilities = implode(', ', $_POST['facilities']);

	//Create and run the query
        $query = "INSERT INTO production (cartons, areaha, tonnage, domestic_sales, exports, facilities)
                  VALUES ('$cartons', '$areaha', '$tonnage', '$domestic_sales', '$exports', '$facilities')";
        debug("Insert Query: {$query}");
        mysqli_query($dbc, $query) or die ('Data not inserted.');
        mysqli_close($dbc);
}
}

if ($output_form) {
    debug("Data not posted or validation failed. Show the form.");
    //Include the form
}

?>

Link to comment
Share on other sites

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.