Skip to content

Instantly share code, notes, and snippets.

@jaredrummler
Last active May 27, 2022 16:20
Show Gist options
  • Save jaredrummler/2bfcf48b48d3fefd50c2 to your computer and use it in GitHub Desktop.
Save jaredrummler/2bfcf48b48d3fefd50c2 to your computer and use it in GitHub Desktop.

Revisions

  1. Jared Rummler revised this gist Mar 17, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion exportcsv.php
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    <?php
    $db_con = mysqli_connect("localhost", "username", "password", "database");
    $result = $db_con->query('SELECT * FROM registered_scouts');
    $result = $db_con->query('SELECT * FROM some_table');
    if (!$result) die('Couldn\'t fetch records');
    $num_fields = mysqli_num_fields($result);
    $headers = array();
  2. Jared Rummler created this gist Mar 17, 2015.
    22 changes: 22 additions & 0 deletions exportcsv.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    <?php
    $db_con = mysqli_connect("localhost", "username", "password", "database");
    $result = $db_con->query('SELECT * FROM registered_scouts');
    if (!$result) die('Couldn\'t fetch records');
    $num_fields = mysqli_num_fields($result);
    $headers = array();
    while ($fieldinfo = mysqli_fetch_field($result)) {
    $headers[] = $fieldinfo->name;
    }
    $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;
    }
    ?>