I'm trying to output/write mysql SELECT results to a text file. The SELECT statement results are three records but when i use fwrite to write these results to a textfile, only one record is written. What can i be possibly be doing wrong? Here is the code snippet

<?php

include "data.php";
$con=dbConnect();
$query="select * from manuscript where month(pubcom_submission_date) = month(now()) order by manuscript_id desc";
$sql=$con->prepare($query);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
        while ($row = $sql->fetch()){
        $list[]= $row['authors'] .','.$row['title'].','.$row['year'].','.$row['journal'];

        }//print_r($list);


foreach($list as $line){
echo "$line<p>";
print_r($line);
//echo "here";
}

$myfile = "/home/alex/Documents/biblio.txt";
$handle = fopen($myfile, 'w') or die('cannot open file: '.$myfile);
$data = $line;
fwrite($handle, $data);

?>

Hi,
it happens because fwrite() is outside the loop and will write the last vallue assigned at $line. Use fputcsv():

Look at the first example, it does what you need.

Hi
Thank you for the response. Unfortunately fputcsv() returns nothing but after changing the code to this, i get the results that i want.

$myfile = "/home/alex/Documents/biblio.txt";
$handle = fopen($myfile, 'w') or die('cannot open file: '.$myfile);

foreach($list as $line){
echo "$line<p>";
print_r($line);
//echo "here";

$data = $line;
fwrite($handle, $data);
}

What i have changed is that i have put fwrite() inside the loop. I also defined, the file and handle variables outside the loop. This two actions give the results i wanted

Good, with fputcsv() you can do:

$list = $sql->fetchAll(PDO::FETCH_ASSOC);
$f = fopen('file.txt', 'w');

foreach($list as $line)
    fputcsv($f, $line);

fclose($f);

You need fetchAll() because you need an array, fetch() instead will return a single row of the result set. Bye!

Thank you very much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.