Search code examples
phpfputcsv

PHP | fputcsv : generated file only populated with field header, but no records


I can't figure out why this code only generate a file with the field headers, but no records.

File content :

"Article ID",Shoppergroupname,"Promotion Price",VAT-Code,"Article Currency","Promotion Start Date","Promotion End Date"

As you can see, no record are "exported" and database table is not tempty !

By the way I also would like to get rid of the field header quotes.

Would appreciate if someone would help me to solve this issue. Thanks in advance.

Marc

SOLUTION PROVIDED BY @KateMihalikova

// Create connection
$conn = new mysqli($databasehost, $databaseusername, $databasepassword, $databasename);

// Check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
echo "Connected successfully | ";

// Create filename
date_default_timezone_set('Europe/Zurich');
$today = date("YmdHis"); 
$csvname = "WS_PRICE_IMPORT-".$today.".csv";
$csvfullname = '/var/.../'.$csvname; 


// create a file pointer connected to the output stream
$output = fopen($csvfullname, 'a+');

// output the column headings
fputcsv($output, array('Article ID', 'Shoppergroupname', 'Promotion Price', 'VAT-Code', 'Article Currency', 'Promotion Start Date', 'Promotion End Date'));

 // fetch the data
$sql = "SELECT `Article ID`, `Shoppergroupname`, `Promotion Price`, `VAT-Code`, `Article Currency`, `Promotion Start Date`, `Promotion End Date` FROM jos_temppriceimport";
$result = $conn->query($sql);

if (!$result) {
echo "Unable to execute query in the database : " . mysql_error();
exit;
}

if ($result->num_rows == 0) {
echo "No record found, no record to export in CSV.";
exit;
}

// loop over the rows, outputting them
while ($row = $result->fetch_row()) fputcsv($output, $row);

PS: Fieldname with space are delivered by the dataprovider.


Solution

  • The main problem in your code was mixing of procedural mysql, procedural mysqli, and object-oriented mysqli. They are similar, but can't be mixed.

    We sort out that the main problem was in while loop.

    while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
    

    after iterating a little, there was a problem with object-oriented notation, where object methods are used instead of functions with attributes, but that attribute was left there. http://phpfiddle.org/main/code/jcbx-7c0n

    while ($row = $result->fetch_row($result)) fputcsv($output, $row); // forgotten attribute
    while ($row = $result->fetch_row()) fputcsv($output, $row);        // working just fine