简体   繁体   中英

Inserting multiple checkboxes values to MySQL

I'm coding a back-end of a blog which the poster should choose which category the post should be.

I don't know what to do next, I only have this piece of code which gets all the checkbox(checked) value(es)

php code

 if(isset($_POST['category'])){
   $category = $_POST['category'];
   foreach ($category as $cat=>$value) {
   echo $value;

html code

<input type="checkbox" name="category[]" value="CategoryA"> CategoryA 
        <input type="checkbox" name="category[]" value="CategoryB"> CategoryB
        <input type="checkbox" name="category[]" value="CategoryC"> CategoryC

I just wanted to know how can I insert the value(es)

The best way to do this to create separate table for adding category.

For example :

tid, name, post_id //something you need 

Then each category you need to insert a new row. Here tid is auto increment, name is your category name and post_id is the auto increment field in your blog table.

So you can use LEFT JOIN to fetch the data from the sub table also.

Other way is to serialize the data and insert in a varchar field in you blog table

$serializedData = isset($_POST['category']) ? serialize($_POST['category']) : "";

You can save category value comma separated like this.

$category = is_array($_POST['category']) ? implode(",",$_POST['category']) : '';
echo $category;

There's no one standard way of doing this. It depends on your application and how you'd like to use this information. If it just to show which categories user has selected and there's no individual checks or logic is required, you can convert the values you're getting in a JSON string, and insert it into database. Let's say you have CategoryA, CategoryB, CategoryC, CategoryD, and CategoryE. If user selects CategoryA and CategoryD. Your JSON would something like:

[{"CategoryA":"1"}, {"CategoryB":"0"}, {"CategoryC":"0"}, {"CategoryD":"1"}, {"CategoryE":"0"}]

In the JSON string above, a '0' indicates that the category hasn't been selected and a '1' that it has. Alternatively, if you have a specified number of categories and they don't get changed that often, you can only add the categories in a JSON that the user has selected. You don't have to write this JSON yourself, just create an array with following specifications

$Array['CategoryA'] = 1;

. . .

$Array['CategoryE'] = 0;

When you've made your array, simply use a PHP function json_encode($ArrayToEncode) and viola! You've got a JSON object. Hope it answers your question. If you have any confusion, please feel free to ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM