Checkbox Fields

Someone has whose tell me the method of store more than one checkbox field item in MySQL Database using PHP.
For example;

in checkbox
Heart Hair Eye Brain

in those i want to write twobody part in my sql database as:

id body_part
2 Heart,Brain

As soon as possible please tell me the PHP code…
I will be thankful to you…

You shouldn’t be storing them as a comma separated list - make them separate rows.

id body_part
2 Heart
2 Brain

I agree with felgall but if for what ever reason you do you can name each checkbox something like body_part. This will give us an array to work with in the POST data. Then all you need to do is run a:

 implode( ',', $_POST[ 'body_part' ] )

before you insert it into the database.

I agree with felgall. storing comma separated values in a db field is very, very poor database design.

True, you can use implode and explode etc. to work with the results, but unless this is going to be a very simple table and remain that way you’re asking for trouble and the inefficiency of the db design will soon become apparent.

That is, you’re having PHP do extra work it shouldn’t need to do, and it won’t be scalable for long.

OK, so what is the best way to store an array in a DB table, and also retrieve that data as an array?
I currently have a similar thing, the checkboxes create an array which I’m converting to a comma separated list for storage. Then I explode list back to an array when read. It works, but if there is a better way…

You could serialize the array. More information in the docs

@SamA74 using @felgalls example, to get a list of body parts belonging to the person whos’ id is #2 you would do a mysql select.

id | body_part
2 | Heart
2 | Brain

SELECT from body_parts where id = 2

That will give you a mysql result set which can be an array, which you then loop through.

But, critically, this also permits you to very efficiently show all the users who have a brain.

SELECT id from body_parts where body_part = 'Brain'

Whereas in the OPs original example you would have to do some kind of text search on the body_parts field.

If you had a table called ‘people’ where the id person #2 for example was “Fred Flintstone” you could ostensibly retrieve the name of the people who had a brain with a single query using a JOIN

example people table rows:

id | name
2 | Fred Flintstone

SELECT from people as p
LEFT JOIN body_parts as bp
bp.body_part = 'Brain'

The term you want to read up on is called Database Normalization, and using a string such as ‘Heart’ and ‘Brain’ is an example of using a natural key.

Lights are on tree, dogs walked, wifey making mince pies, signing off. Have a nice one wherever you are. (your) God bless.