Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Ray Mak
Ray Mak
4,667 Points

Need help with exporting mysql data using php to csv downloadable file

Hello,

I created a web page that executes request from mysql and prints it on web page. I also created a export submit button to export mysql query in csv format file. When I select values and then click on export buttons, I get nothing and page gets refreshed.

Here is the link of my site: rahil.me/index.php

Here is the code:

These are the buttons: HTML code: input type="submit" name="search" value="Search" input type="submit" name="export" value="Export"

Here is the php code:

if (isset($_POST['export'])) {

if (empty($_POST['service'])) {

    echo "Please select service in dropdown" . "</br>";

}

else {

    $service = $_POST['service'];

}

if (empty($_POST['environment'])) {

    echo "Please select Environment in dropdown" . "</br>";

}

else {

    $env = $_POST['environment'];

}

if ((!empty($service)) && (!empty($env))) {

$sql="SELECT Query Removed";

$result = mysqli_query($con,$sql);

if (!result) {

    die('Error: ' . mysqli_error($con));

}

/*
 * send response headers to the browser
 * following headers instruct the browser to treat the data as a csv file called export.csv
 */

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');

/*
 * output header row
 */

 $headers = array();
 foreach (mysqli_fetch_fields($result) as $field) {
    $headers[] = $field->name;
 }

 echocsv($headers);

/*
 * echo the input array as csv data maintaining consistency with most CSV implementations
 * - uses double-quotes as enclosure when necessary
 * - uses double double-quotes to escape double-quotes 
 * - uses CRLF as a line separator
 */

while ($row = mysqli_fetch_row($result)) {

    echocsv($row);

}

function echocsv($fields)
{
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";
}

} }

So, when I click on export button with all the values, page just gets refreshed and I dont get prompt to download csv file. But when I add above code in separate file, I get prompt to download file. Its only not working when I add the above code in index.php.

Not sure what I am doing wrong here.

1 Answer

Just to be sure, is your form element's action attribute pointing to the php file with this code in it? And it should of course have the method attribute set to POST.

Can you include more of the HTML code being used?

Also, you might want to output plain HTML or text initially to debug your code. And add in some more debugging points, so you can find where in the code it is failing.