Skip to main content
Known Participant
December 3, 2017
Answered

$output lists only one record

  • December 3, 2017
  • 3 replies
  • 3095 views

I have the following code in a php file for exporting data to a csv file.

<?php require_once('../connections/PaSiteGuide.php'); ?>

<?php

// output headers so that the file is downloaded rather than displayed

header('Content-Type: text/csv; charset=utf-8');

header('Content-Disposition: attachment; filename=BOP.csv');

// create a file pointer connected to the output stream

$output = fopen('php://output', 'w');

// output the column headings

fputcsv($output, array('ID','Common Name', 'Scientific Name', 'Breeds', 'Abundance', 'Occurrence', 'Seasonal Status','AOU_Order','AOU Supplement'));

// fetch the data

mysqli_select_db($conn, $database_PaSiteGuide);

$query_rsrows = sprintf('SELECT birdsofpa.ID, birdsofpa.CommonName, birdsofpa.SciName, birdsofpa.Breeding, birdsofpa.Abundance, birdsofpa.Occurrence, birdsofpa.SeasonalStatus,

aou_list.AOU_Order, aou_list.Updated FROM birdsofpa, aou_list WHERE birdsofpa.ID =  aou_list.SPNO ORDER BY aou_list.AOU_Order ASC');

$rows = mysqli_query($conn, $query_rsrows) or die(mysqli_connect_error());

$row_rsrows = mysqli_fetch_assoc($rows);

$totalRows_rsrows = mysqli_num_rows($rows);

// loop over the rows, outputting them

while ($rows = mysqli_fetch_assoc($rows)) fputcsv($output, $rows);

?>

<?php

mysqli_free_result($rows);

?>

It outputs the file, but only the column titles and one row of data ( and the row it puts out is not the first row based on the ORDER BY specified).

So how do I make it do all of the rows and in the correct order?

This topic has been closed for replies.
Correct answer osgood_

Yes. Thank you.

Frank


This should give you what you need, it's just a tweak of your original code.......

<?php

// connect to database - change details to those of your own

$conn = new mysqli('servername' , 'username' , 'password' , 'database_name');

// output headers so that the file is downloaded rather than displayed

header('Content-Type: text/csv; charset=utf-8');

header('Content-Disposition: attachment; filename=BOP.csv');

// create a file pointer connected to the output stream

$output = fopen('php://output', 'w');

// output the column headings

fputcsv($output, array('ID','Common Name', 'Scientific Name', 'Breeds', 'Abundance', 'Occurrence', 'Seasonal Status','AOU_Order','AOU Supplement'));

// get data to display on page

$list_data = $conn->query("SELECT birdsofpa.ID, birdsofpa.CommonName, birdsofpa.SciName, birdsofpa.Breeding, birdsofpa.Abundance, birdsofpa.Occurrence, birdsofpa.SeasonalStatus,

aou_list.AOU_Order, aou_list.Updated FROM birdsofpa, aou_list WHERE birdsofpa.ID =  aou_list.SPNO ORDER BY aou_list.AOU_Order ASC") or die($conn->error);

$num_rows = $list_data->num_rows;

// loop over the rows, outputting them

while ($row = $list_data->fetch_assoc()) fputcsv($output, $row);

?>

3 replies

Ussnorway7605025
Legend
December 5, 2017

Linux is case sensitive

B i r n o u
Legend
December 4, 2017

well if your goal is to export a brand new create CSV file and integrating Headers ROW/COLS in the CSV , I wont be able to help you the way you do it... (I don't say that it is not possible that way, But pêrsonnaly I don't use it that way

first I create array that handles the different headers needed depending on the export template

say

$headers = array( "headertype1" => array(), "headertype2" => array());

on each array I have two definitions,

1 - the fields to be extracted, and 2 the Label of those fields

those definitions are string semi colon separation

i.e

"headertype1" => array("db_fields" => 'field1;field2;field3', "db_headers" => 'label 1; label 2; label 3');

well to write the CSV

first connect your database

include_once('/'.trim( $_SERVER['DOCUMENT_ROOT'], '/' ).'/shared/php/__connect.php');

I often a shared space for deploying the PHP

the trim is to allow the document root to be extracted as well from a xampp localhost as from linux host

then before creating the CSV file I set the appropiate headers/cols

first I set the RS choice corresponding to the header type

and the liste of datas to be choose in (if needed... not necessary... it acts like a subfilter)

$RS = 'headertype1'; // or whatever choice

$liste = 'x,y,z';

$fields = explode(';',$headers[$RS]['db_fields']);

$entete = $headers[$RS]['db_headers'];

then I apply the SQL queries

$sql ="SELECT * FROM `tab_something` WHERE `ch_tab_id` IN (".$liste.") ORDER BY `ch_tab_id` ASC"; // this a foo exemple

then I execute the request

$items = $dbh->prepare($sql);

$items->execute();

$CSV = '';

the loop is made to fill up the CSV as a string

I choose the star * for beeing a line separator... you can also use the å which is also a caracter that is not use in general... except if you're physician... or danish...

while($item = $items->fetch(PDO::FETCH_OBJ)){

        $CSVtemp  = '';

        foreach ($fields as $field) {

            if ($CSVtemp != '') {

                $CSVtemp .= ';';

            }

            $CSVtemp .= $item->{$field};

           

        }

        if ($CSV != '') {

            $CSV .= "*";

        }

        $CSV .= $CSVtemp;

    }

  

the you add the headers

$CSV = $entete . '*' . $CSV;

if you need the BOM Sign... add the following...

$CSV="\xEF\xBB\xBF".$CSV;

name you CSV file

    $filename = 'export_'.date('Y-m-d__h-i-s').'.csv';

create the path and open the file

    $fichier = '../../EXPORTS/'.$filename;

    $fp = fopen($fichier, 'w');

create all the declarations depending on the specific char used earlier * or å...

    $declarations = explode('*',$CSV);

now write all your lines in a loop

    foreach ($declarations as $declaration) {

        $record = explode(';',$declaration);

        fputcsv($fp, $record, ";",'"');

    }

   

fclose($fp);

echo $filename;

that should do the job... at least it works like a charm since I use it...

now the fact of applying the array on top... let you play with as many template as you will need for your client needs

Nancy OShea
Community Expert
Community Expert
December 3, 2017

See if this helps.

<?php

$con = mysqli_connect("localhost","your_username","your_password") or die ("could not connect to mysql");

mysqli_select_db($con, "your_database") or die ("no database found");

$result = mysqli_query($con,"SELECT * FROM your_tablename ORDER BY your_fieldname");

$row = array($result);

$fp = fopen('your_csv_file.csv', 'w');

while($row = $result->fetch_assoc()) {

    //Fetch data as an associate array so we can reference field by name

    fwrite($fp, implode(',', $row) . "\r\n");

}

fclose($fp);

mysqli_close($con);

?>

Nancy O'Shea— Product User & Community Expert
pabirdsAuthor
Known Participant
December 3, 2017

I tried your suggested code -- see below, but it tried to save it with the name of the php file rather than the csv filename that I entered (BOP).

When I tried to open the downloaded file with a spreadsheet, it was blank.

<?php require_once('../connections/PaSiteGuide.php'); ?>

<?php

mysqli_select_db($conn, $database_PaSiteGuide)or die ("no database found");

$result = mysqli_query($conn,"SELECT birdsofpa.ID, birdsofpa.CommonName, birdsofpa.SciName, birdsofpa.Breeding, birdsofpa.Abundance, birdsofpa.Occurrence, birdsofpa.SeasonalStatus,

aou_list.AOU_Order, aou_list.Updated FROM birdsofpa, aou_list WHERE birdsofpa.ID =  aou_list.SPNO ORDER BY aou_list.AOU_Order ASC");

$row = array($result);

$fp = fopen('BOP.csv', 'w');

while($row = $result->fetch_assoc()) {

    //Fetch data as an associate array so we can reference field by name

    fwrite($fp, implode(',', $row) . "\r\n");

}

fclose($fp);

?>

Nancy OShea
Community Expert
Community Expert
December 3, 2017

I'm using the exact same code I posted and it works great for me on Linux server.

The PHP script is in a PHP file.   Results are posted to an existing CSV file when the PHP script is run.

My SQL query is less complicated than yours.  That might be where things are breaking down.  But that's only a guess.

Nancy

Nancy O'Shea— Product User & Community Expert