Can anyone help me on how to store checkbox values in my database?

I have a site which is a student registration form and I need to store his/her interest/s in my database.

Interest/s are my checkboxes which contains sports, music, entertainment and adventure.

Please help me!

Thanks!

Of course there could be many approaches , one of them is :

Create a table for interests (e.g. interests) that has an ID and a TITLE (there could be many more there as for example if you like to deactivate or many more)

I suppose that you already have a table for students (lets call it students) that has a unique id for each of them.

So what left to do is to create a map table (e.g. students_interests) where you will store those pairs (student ID and interest ID) , if you believe that this connection may mean more in future it’s a good idea to have also an ID for it.

It depends on how you want to process the information after it has been stored. If you plan to use complex queries like "students who like (music AND (sports OR adventure))" then the only viable solution is 1:n - having a db table of relationships between students and their interests. A record would exist for each student and each of their interest. (Not for interests they don't have.)

A simpler model could be used if you only need to ask simple questions like "does this student like music? yes/no", or get me all students who like music. You could then have a single attribute for a student where you'd list all of his interests, comma separated.

Name    Interests
Petr    sports,entertainment

The query would then look like this:

SELECT * FROM students WHERE CONCAT(',', interest, ',') LIKE '%,music,%'

If speed is crucial then you could make the attribute of type SET (MySQL only afaik) and search it using FIND_IN_SET(). The disadvantage is that you have to list all possible values when creating the table so if you need to add/remove some, you have to alter the table structure.

@jkon -
can you give me an example code which stores checkbox values to database and retrieving the checkbox for updates (ticked already for chosen boxes). Please?

Thanks a lot!

THANKS A LOT GUYS! Already solved my problem. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.