1
build excel file php mysql
CGuild1.com > Tips & Tricks > build excel file php mysql

Create an Excel File with a PHP Query

I use this to create a download Excel button for many different reports. It will take the php query you are using and generate a downloadable Excel spreadsheet.

This particular code is using the now outdated mysql_connect. It is for a specific client that wishes to not update to pdo or mysqli. <?php     // Connection
    $conn = mysql_connect('localhost','USERNAME','PASSWORD');
    $db = mysql_select_db('DBNAME',$conn);
    // File Name
    $filename = "report.xls";
    
    // Download file
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");
    $user_query = mysql_query('SELECT * FROM table_name WHERE blah = 'blah' GROUP BY blah ');
    
    // Write data to file
    $flag = false;
    while ($row = mysql_fetch_assoc($user_query)) {
        if (!$flag) {
            // display field/column names as first row
            echo implode("\t", array_keys($row)) . "\r\n";
            $flag = true;
        }
        echo implode("\t", array_values($row)) . "\r\n";
    }
?>
©2024 CGuild1.com