Ben Junior Ben Junior - 6 months ago 13
MySQL Question

How to store answers to a MySQL table

I want to take Stack Overflow as an example. Now, there's a question posted and let's say they store the following things to database.

question_ID
question_title
question_body
question_asker
question_date


But there are 2 things left, the comments and the answers. So my question is "How do I store them to the database?" I mean, I don't think that 5 or probably 10 article-like answers are stored in just a cell.

Answer

The answers and the commments will be stored in different tables, like so :

Database

questions

question_ID question_title question_body question_asker question_date

answers

answer_ID answer_title answer_body answer_asker answer_date question_ID

comments

comment_ID comment_title comment_body comment_asker comment_date answer_ID

Here is an example of PHP code fetching the data using INNER JOIN :

PHP

$dbh = new PDO('mysql:host=localhost;dbname=stackoverflow', $user, $pass);
$query = 'SELECT * from questions INNER JOIN answers ON answers.question_ID = question_ID INNER JOIN comments on comments.comment_ID = answer_ID';
foreach($dbh->query($query) as $row) {
    print_r($row);
}

Complete schema of stackoverflow database : Database schema