<?php

//Our MySQL connection details.
$host = 'localhost';
$user = 'supportf_user';
$password = 'cO?.dTHbAXo{';
$database = 'supportf_db';

//Connect to MySQL using PDO.
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);

//Create our SQL query.SELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY]
$sql = "SELECT asset_user, designation, device_name, brand_name, tagging_no, date_issued 

FROM apl_asset, apl_asset_brand, apl_device_asset

WHERE apl_asset.brand_id = apl_asset_brand.brand_id 

AND apl_asset.device_id = apl_device_asset.device_id ";

//echo STR_TO_DATE('12/15/2008', '%m/%d/%Y');
/*$sql = "SELECT lastname, firstname, tag
        FROM drivers, vehicles
        WHERE drivers.location = vehicles.location";
        
        */

//Prepare our SQL query.
$statement = $pdo->prepare($sql);

//Executre our SQL query.
$statement->execute();

//Fetch all of the rows from our MySQL table.
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

//Get the column names.
$columnNames = array();
if(!empty($rows)){
    //We only need to loop through the first row of our result
    //in order to collate the column names.
    $firstRow = $rows[0];
    foreach($firstRow as $colName => $val){
        $columnNames[] = $colName;
    }
}

//Setup the filename that our CSV will have when it is downloaded.
$fileName = 'mysql-export.csv';

//Set the Content-Type and Content-Disposition headers to force the download.
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

//Open up a file pointer
$fp = fopen('php://output', 'w');

//Start off by writing the column names to the file.
fputcsv($fp, $columnNames);

//Then, loop through the rows and write them to the CSV file.
foreach ($rows as $row) {
    fputcsv($fp, $row);
}

//Close the file pointer.
fclose($fp);