Jerry Jones
Jerry Jones

Reputation: 796

Create a report from multiple tables in php, MySql

We have four tables which containe respectivle the following datas,

1. tbl_user [user_id, user_name, user_email, user_country]
2. tbl_questions [survey_id, survey_question, posted_on]
3. tbl_answers [answer_id, question_id, answers]
4. tbl_survey_result [user_id, question_id, answer_id, timestamp]

We want to generate an excel report based on these data as figured below,

survey_result_dd_mm_yyyy.xls

sr_no | User_id | User_name | User_Email | User_Country | Question_1 | Question_2... ( n number of questions)
1     | 123456  | John Doe  |[email protected] | India        | His Answer | Another Ans...

So, how can we generate this report using mysql, php?

Upvotes: 1

Views: 901

Answers (1)

Simas Joneliunas
Simas Joneliunas

Reputation: 3118

I would approach it by forming a basic query like this to get the user id:

select u.user_id from tbl_user u

then, assuming we get the user id data in $users variable i would run the following query in a foreach ($users as $user) loop:

select u.user_id, u.user_name, u.user_email, u.user_country, q.survey_question, a.answers from tbl_user u
inner join tbl_survey s on u.user_id = s.user_id
inner join tbl_answers a on a.answer_id = s.answer_id
inner join tbl_questions q on q.question_id = s.question_id
where u.user_id = %user
order by u.user_id, q.survey_id'

Finally, parse the query into a user-question array.

Exporting to excel question was already answered by Baba in https://stackoverflow.com/a/10424955/3986395 and i will share his answer here:

header("Content-Disposition: attachment; filename=\"demo.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
foreach ($array as $data)
{
    fputcsv($out, $data,"\t");
}
fclose($out);

Finally, if you have millions of users you might not want to run the query in a foreach loop and instead write a combined query to get all user data. This query would give you user_id-answer records and you would need additional processing logic in php to merge the data into required array

select u.user_id, u.user_name, u.user_email, u.user_country, q.survey_question, a.answers from tbl_user u
inner join tbl_survey s on u.user_id = s.user_id
inner join tbl_answers a on a.answer_id = s.answer_id
inner join tbl_questions q on q.question_id = s.question_id
where ..
order by u.user_id, q.survey_id

Upvotes: 2

Related Questions