Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting table to CSV via php button

Tags:

php

mysql

csv

I am really new to php and everything I have learned is from my school textbook and online research. With that said I am trying to complete an assignment and I am stuck on the last part. for the final part the assignment says to "Create a PHP script that will dump the contents of the employee table into CSV text file that has comma separated values for each record. Each new record should begin on a new line". I have tried many online tutorials but none of them teach how to put this event in a button. I am including my code so you can see the mess I have. It's not to bad but I am sure I can do the same task with much less code. Again I am just starting out and this is the best I can do for now. Could anyone give any suggestions on how this could be done. I have my button on line 140. I also used a db_connect() function so i don't have to write it many times. I can peon use this to read the database before I save as a csv.

Any suggestions would be greatly appreciated. Be warned It's a lot of code to follow.

    <h2>Employee Search</h2>
    <form action="Draft.php" name="dbToCSV" method="GET">
        <input type="submit" name="dbToCSV" value="Export Database to CSV" <?php if     (isset($_GET['dbToCSV']))
                    {
                        //Do this code
                    }
                    else
                    {
                        echo "Error!";
                    } ?>><br />

    </form>
    <form action="Draft.php" method="GET">
        By name: <input type="text" name="searchName">
        <input type="submit" value="Search Name"><br />
    </form>
    <form action="Draft.php" method="GET">
        By language: <input type="text" name="searchLang">
        <input type="submit" value="Search Language"><br />
    </form>
like image 311
mcvargas Avatar asked Feb 21 '14 02:02

mcvargas


People also ask

How do I export data from a table to a CSV file?

Select the table of the database that you want to export and click on the Export tab from the right side. Select the CSV format from the Format drop-down list and click on the Go button. Select the Save File option and press the OK button.

How do I create a CSV file and download a PHP script?

$fh = fopen('somefile. csv', 'w') or die('Cannot open the file'); for( $i=0; $i<count($arr); $i++ ){ $str = implode( ',', $arr[$i] ); fwrite( $fh, $str ); fwrite( $fh, "\n" ); } fclose($fh);

How do I export data from SQL to Excel using PHP?

php // Connection $conn=mysql_connect('localhost','root',''); $db=mysql_select_db('excel',$conn); $filename = "Webinfopen. xls"; // File Name // Download file header("Content-Disposition: attachment; filename=\"$filename\""); header("Content-Type: application/vnd.


2 Answers

It's 2017 and mysqli is more common than mysql now. So here's a mysqli version of Josh Liptzin's answer:

<?php

/* Attempt MySQL server connection. */  
$connection = mysqli_connect($database_server, $database_username, $database_password, $database_name);

// Check connection
if($connection === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$query = "SELECT * FROM Employee_data";
$result = mysqli_query($connection, $query);

$number_of_fields = mysqli_num_fields($result);
$headers = array();
for ($i = 0; $i < $number_of_fields; $i++) {
    $headers[] = mysqli_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, $headers);
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

function mysqli_field_name($result, $field_offset)
{
    $properties = mysqli_fetch_field_direct($result, $field_offset);
    return is_object($properties) ? $properties->name : null;
}

?>
like image 173
Paul Chris Jones Avatar answered Nov 02 '22 00:11

Paul Chris Jones


You are literally trying to put the PHP code inside the HTML button. The button can simply be a link to another page (like dump.php), which contains some PHP like the following:

Link:

<a href="dump.php" target="_blank">Download employee data</a>

dump.php:

<?php

$result = mysql_query('SELECT * FROM `employee_data`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
    $headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, $headers);
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

?>

Code source: PHP code to convert a MySQL query to CSV

For your own sake you shouldn't copy and paste the above code into your assignment - there's a world of difference between the code you posted and the code above that the grader will instantly pick up on.

like image 32
Josh Liptzin Avatar answered Nov 01 '22 23:11

Josh Liptzin