I am using PHP to query a MYSQL database, and I am trying to output the data to an excel file.
I have used phpexcel, csv, etc. With each i have successfully been able to output the data to an excel file, but I can’t seem to transpose it in the excel (transpose- flip all columns into rows, and rows into columns)
I can’t find any tutorials to help me out.
My question is, is there a way to use php to transpose those rows and columns from MYSQL and import them into an excel file?
thanks!
CODE:
exportMysqlToCsv($tablename,$tokenmain, $id);
function exportMysqlToCsv($tablename,$tokenmain, $id, $filename = 'Results.csv'){
$sql_query = "select * from $tablename where token=1";
// Gets the data from the database
$result = mysql_query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
//trying to transpose the data
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);}
//inserting it into the excel file
while ($row = mysql_fetch_assoc($result)) {
if ($first) {
fputcsv($f, array_keys($row));
$first = false;
}
fputcsv($f, $row);
}
} //end while
Database sample:
=======================================
| Male/female | Favorite artist |
=====+========+===============+=======|
| F | Britney Spears |
|-------------------------------------|
What I want it to look like:
=====================================
|Question | Answer |
=====+========+===============+=====|
| Male/female | F |
|----+--------+---------------+-----|
| Favorite artist | Britney Spears |
|----+--------+---------------+-----|
HUGE NOTE: There is no changing the database/hardcoding out the array in php. I want it all dynamic and the database is going to stay the way it is
To answer my question this is my code using PHPExcel:
Switch up the columns (col) and rows (row), so that the columns in the database become the rows in the excel file and the same for the rows to columns.