What am I doing wrong? MySQL DB to CSV Export

Cannot figure out what the hell I’m doing wrong. Connecting to the database fine, can receive the .csv file via the browser but nothing is in the file. Can anyone spot what I might be missing?

    function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {
        if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        $result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );
        if($headers) {
            // output header row (if at least one row exists)
            $row = mysql_fetch_assoc($result);
            if($row) {
                fputcsv($fp, array_keys($row));
                // reset pointer back to beginning
                mysql_data_seek($result, 0);
        while($row = mysql_fetch_assoc($result)) {
            fputcsv($fp, $row);

    // Using the function
    $sql = "SELECT * FROM `leads` WHERE marketer = 'Michael Froseth'";
    // $db_conn should be a valid db handle
    $db_conn = new MySQLi('localhost', 'freesales', '*****', 'freesalessystem');
    // output as an attachment
    query_to_csv($db_conn, $sql, "FREESALESSYSTEM-" . date("Y-m-d") . ".csv", true);

    // output to file system
    query_to_csv($db_conn, $sql, "FREESALESSYSTEM-" . date("Y-m-d") . ".csv", false);

What happens if you set the 5th arg, $headers to false?



to check there are any matching results