I'm using php. I want to export some data from mysql database to xls file.
The table Answers i have in mysql database:
Table Answer:
Id Registration_id Question_id Answer
1 Reg01 1 John
2 Reg01 2 Smith
3 Reg01 3 [email protected]
4 Reg02 1 Rachel
5 Reg02 2 Smith
6 Reg02 3 [email protected]
The result i obtain from the code below is not the result i expected. The headers are displayed correctly but the answers are displayed in the same line...
Name SecondName Email John Smith [email protected] Rachel Smith [email protected]
I want this result:
Name SecondName Email
John Smith [email protected]
Rachel Smith [email protected]
Can you tell me how can I do this?
Thanks.
Here is the code:
$conn = mysql_connect("localhost","form","pass");
$db = mysql_select_db("form",$conn);
$query = "SELECT DISTINCT wp_events_question.question as qst, wp_events_answer.answer as ans
FROM wp_events_question, wp_events_answer
WHERE wp_events_question.id = wp_events_answer.question_id";
$query2 = "SELECT wp_events_question.question as qst, wp_events_answer.answer as ans
FROM wp_events_question, wp_events_answer
WHERE wp_events_question.id = wp_events_answer.question_id and wp_events_detail.id = wp_events_attendee.event_id AND wp_events_attendee.id = wp_events_answer.attendee_id";
$result = mysql_query($query) or die(mysql_error()); //Headers
$result2 = mysql_query($query2) or die(mysql_error()); //Answers
//Headers
$tbl= " <table border='1'>";
$tbl= $tbl . "<tr height='50px'>";
while($row = mysql_fetch_array($result))
{
$tbl= $tbl . "<td WIDTH='50px' align='center'>".$row['qst']."</td>";
}
//Answers
$tbl = $tbl . "</tr>";
$tbl = $tbl . "<tr>";
while($row2 = mysql_fetch_array($result2))
{
$tbl= $tbl . "<td WIDTH='50px' align='center'>".$row2['ans']."</td>";
}
$tbl = $tbl . "</tr>";
$tbl = $tbl . "</table>";
header("Cache-Control: no-stor,no-cache,must-revalidate");
header("Cache-Control: post-check=0,pre-check=0", false);
header("Cache-control: private");
header("Content-Type: application/force-download");
header("Content-Disposition: inline; attachment;filename=Reservations.xls");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
print $tbl;
$tbl .=instead of$tbl= $tbl .? For the rest, I have no Excel so I can't test this, but I assume generating a proper xls(x) file with one of the many libraries, or failing that, writing an .csv file is more easily understood by Excel then HTML.