krifur
krifur

Reputation: 890

how to store muliple checkbox results into a mysql table

I would like to know which is the better way to store the result of a multiple checkboxes form into a mysql table.

I can see two solutions but perhaps there is other

-One field by checkbox

-One field for all checkboxes with serialize data

thx

Upvotes: 0

Views: 1297

Answers (3)

hypervisor666
hypervisor666

Reputation: 1275

I agree with Vitor Mello, create a table where each checkbox maps to a special field. This is not that much overhead, so save yourself the trouble.

Also I'm guessing that you are using a form to post these answers back to the server?

If so here is a tip:

When you post a form that contains checkboxes to a server side PHP page, you check to see of the check boxes are set like so:

HTML:

<form>
<input type="checkbox" name="chk1" />
<input type="checkbox" name="chk2" />
<input type="submit" name="myChkSubmit" />
</form>

PHP POSTBACK Handler:

<?php

//Correct way to retrieve your checkboxes

$chk1 = FALSE;
$chk2 = FALSE;

if( isset($_POST['chk1']) )
{
  $chk1 = TRUE;
}

if( isset($_POST['chk2']) )
{
  $chk2 = TRUE;
}

//WRONG WAY

$chk1 = FALSE;
$chk2 = FALSE;

if( isset($_POST['chk1']) )
{
  $chk1 = $_POST['chk1']; //This will always evaluate to "undefined"
}

if( isset($_POST['chk2']) )
{
  $chk2 = $_POST['chk2']; //This will always evaluate to "undefined"
}

//NOTE: the reason the above example is incorrect is because the form will indicate checked 
//      status of a check box by setting the POST array element, but does not set a value 
//      for that element.  If the element is set in POST it was checked, if it is not set,
//      it will not be a recognized index in the POST array. 

Upvotes: 2

Vitor M
Vitor M

Reputation: 967

  • One field by checkbox is definitely NOT they way to go, that will cause you more trouble than anything else.

  • If you defintely need to store the results in the same table, serialization is the best, as long as you know you wont be able to make SQL queries based on those values.

  • The best thing to to is to create a NxN table, linking your original table to another table where you will have the list of possible checkbox values. Thats also the recommended normalization for this case.

Upvotes: 2

Pete Wilson
Pete Wilson

Reputation: 8694

Just speaking for myself: I would find it far, far easier to query stored checkbox values later if I took the trouble to store them one per column in the first place. But of course YMMV.

Storing the values one per column also makes those values normalized, which is (or should be) one of my primary goals in designing the table.

Upvotes: 2

Related Questions