Allen S
Allen S

Reputation: 3549

PHP: Adding dynamic number of values into a MySQL database

I've got a page with text fields where the user can input data (in our situation they are questions).

It would look look something like this:

 ___________________________________
|   Enter your question...          |  +
|___________________________________|  

If the user clicks '+' then another field comes up:

 ___________________________________
|   User's first Question..         | 
|___________________________________|  
 ___________________________________
|   Enter your next question...     |  +
|___________________________________|  

...And so on. Each of these questions need to be stored in the database, but with the number of questions being dynamic (let's say for arguments sake we limit the max number to 100 questions), what's the best way to achieve this? Should I be creating a new column for each question? Wouldn't that really pollute the database? Ideally I'd have just one column in my database called 'Questions' and just store all the questions in that one column. Is that even possible?

Something like this:

++++++++++++++++++++++++++++++++++++++++++++++
+ id |  Questions                            +
++++++++++++++++++++++++++++++++++++++++++++++
+  1 |  My Question 1,MyQuestion,            +
+  2 |  Another Question, And Another one,   +
+  . |  ......                               +
++++++++++++++++++++++++++++++++++++++++++++++

*EDIT* To make it clear - I need to be able to retrieve each of those questions later on and be able to isolate each one individually (e.g. as a PHP array).

*EDIT2* Additionally because the set of questions are per each user, the bundle of questions need to remain in ONE row. I.e. I can't add the questions in their own rows. In the example above, ID1 is an individual user and My Question 1 and MyQuestion are that user's questions.

Upvotes: 0

Views: 123

Answers (3)

J2D8T
J2D8T

Reputation: 825

An option you can try as well would be to split it up by creating another table. So to be clear one table for user and another one for question.

In table user you can have a user_id and maybe username and in table question you can have a unique_id, the question and then a foreign key constraint referencing the user of the question.

This way you can access them individually or all together.

Upvotes: 0

Lakmal Vithanage
Lakmal Vithanage

Reputation: 2777

In this situation, you can use Document based NOSQL solution like MongoDB, or create a table with id , user_id and question.

Upvotes: 0

Furunomoe
Furunomoe

Reputation: 1404

The simplest one, I believe, is to made your database table like this :

++++++++++++++++++++++++++++++++++++++++++++++
+ id | user_id | question                    +
++++++++++++++++++++++++++++++++++++++++++++++

So it does not matter how many question a user will have.

Upvotes: 1

Related Questions