alsabsab
alsabsab

Reputation: 1311

Putting multiple checkbox answers in a MySQL database

I have a checkbox asking the user to put his/her favorite courses. I want to store all the selected courses in one column separated by delimiters in MySQL database

This is the way I insert it into mysql database. How should I be doing this?

$sql="INSERT INTO Students(FirstName, LastName,gender,Major,Favorite_courses,GPA,Date_of_reg)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[sex]','$_POST[major]','$_POST[favorite]','$_POST[GPA]',SYSDATE())";

$_POST[favorite] is the field in question.

Upvotes: 0

Views: 517

Answers (3)

Jay Zus
Jay Zus

Reputation: 573

Well, for security and normalization reasons you shouldn't do that.

However, you can do it, if you really want to by using the function serialize() of php.

$myFavorites = serialize($_POST[favorite]);
$sql="INSERT INTO Students  (FirstName, LastName, gender, Major, Favorite_courses, GPA, Date_of_reg) VALUES
('$_POST[firstname]' ,'$_POST[lastname]' ,'$_POST[sex]' ,'$_POST[major]', '$myFavorites', '$_POST[GPA]', SYSDATE())";

You'll be able to unserialize it after you got it from your database with

$serializedCourses = myFunctionToGetItFromMyDatabase();
$unserializedCourses = unserialize($serializedCourses);

What I would do would be to create another table in your database for the Courses, and link it to the user via the user's id. For example you could create as much columns as there is type of courses, and that will make you able to get easily the list of people who like Maths (for example) or even Maths and Geometry.

You won't be able to do that with your solution easily.

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77966

$sql="INSERT INTO Students(FirstName, LastName,gender,Major,Favorite_courses,GPA,Date_of_reg) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[sex]','$_POST[major]','implode(\',\',$_POST[\'favorite\'])','$_POST[GPA]',SYSDATE())";

Upvotes: 3

Marcovecchio
Marcovecchio

Reputation: 1332

If you REALLY want to put all favorite courses into a single field, you can make this field a string, and store the PHP array in it by serializing it. You can use the serialize() function, or JSON, json_encode(), or any other similar method. To retrieve the data, just use unserialize(), or json_decode(), and you will have your array back in PHP.

But keep in mind that using a SELECT statement to filter who likes course foo or course bar, will be quite dificult. The best approach is to follow jeroen's suggestion, normalizing your data.

Upvotes: 2

Related Questions