Page 1 of 1

I want to export data from database to csv format.

Posted: Mon Jun 16, 2014 6:48 am
by learner001
I want to export data from database to csv format.

Code that i am using is (page name-export.php)

Code: Select all

    
    <?php
    // Database Connection
    
    $host="localhost";
    $uname="root";
    $pass="";
    $database = "a2zwebhelp"; 
    
    $connection=mysql_connect($host,$uname,$pass); 
    
    echo mysql_error();
    
    //or die("Database Connection Failed");
    $selectdb=mysql_select_db($database) or 
    die("Database could not be selected"); 
    $result=mysql_select_db($database)
    or die("database cannot be selected <br>");
    
    // Fetch Record from Database
    
    $output = "";
    $table = ""; // Enter Your Table Name 
    $sql = mysql_query("select * from $table");
    $columns_total = mysql_num_fields($sql);
    
    // Get The Field Name
    
    for ($i = 0; $i < $columns_total; $i++) {
    $heading = mysql_field_name($sql, $i);
    $output .= '"'.$heading.'",';
    }
    $output .="\n";
    
    // Get Records from the table
    
    while ($row = mysql_fetch_array($sql)) {
    for ($i = 0; $i < $columns_total; $i++) {
    $output .='"'.$row["$i"].'",';
    }
    $output .="\n";
    }
    
    // Download the file
    
    $filename = "myFile.csv";
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename='.$filename);
    
    echo $output;
    exit;
    
    ?>
     


It is working perfectly but i want another page that can be showed at user end and he can download the file by clicking on a button.. For this purpose the code that i am using is

Code: Select all

    
    <form action="export.php" method="post">
    Please click here to download:
    <input type="button" name="Download" value="Download"> 
    </form>
    


I think i have done something wrong because the two pages are not getting linked to each other. Whenever i am clicking on the download button it remains on the same page..
Can plz someone point out the error.

Re: I want to export data from database to csv format.

Posted: Mon Jun 16, 2014 12:39 pm
by requinix
You said the first file was named "name-export.php" but you have your form pointing to "export.php". That could certainly be the problem.

Re: I want to export data from database to csv format.

Posted: Mon Jun 16, 2014 4:09 pm
by Christopher
You can fetch records and loop, however I would recommend creating a temporary file name, using "SELECT * INTO OUTFILE '/tmp/$filename' WHERE ...", sending the file to the browser and the deleting the file. The SELECT INTO OUTFILE syntax allows you to set the field and line delimiters, escaping, quoting, etc. I think it defaults to tab-delimited.