drummer392 drummer392 - 4 months ago 16
MySQL Question

Storing Multiple Checkbox Data in MySQL Database with PHP

I want to have multiple checkbox values be stored into one field in a database. (Ex. 1, 24,56,100). I am wanting to know how I can make this happen, and how does PHP read these values from the database if I want to call variables in a query?

Basically I am creating a blog app (for fun and experience) and I want the user to be able to change the visibility of each blog post through checkboxes. I know you are probably thinking why don't I just have a visibility field for each blog post. I understand why it is not recommended to do this, but I can't think of any other way to do this. To explain a bit more: I want to attach this application to a CMS I have already built, and basically I have a table with blog posts, and then I want the user to be able to go to different pages within their site and add a blog. Well, what if the user wants to use the same blog on 3 different pages, but only wants certain posts to show on each page. So this is why I am confused right now.


Even though I am not in favor of saving data like that but here is what you can do, if you really want to do it that way. I suggest you have a denormalized table and store your vals there

in your HTML you can have your checkboxes like this (considering you are storing ids of some sort)

<input type="checkbox" name="ids[]" value"1" />
<input type="checkbox" name="ids[]" value"24" />
<input type="checkbox" name="ids[]" value"56" />
<input type="checkbox" name="ids[]" value"100" />

On you php side you can use function implode to form ids into a string as shown below (considering you are doing a POST)

$ids = implode(",",$_POST["ids"]);

Where you read from the database you can transform the value from db to an array like this

$ids_array = explode(",",$row->ids);

I hope this helps