0

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);

?>
2
Contributors
4
Replies
20
Views
2 Years
Discussion Span
Last Post by Amaina
0

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

Edited by Amaina

1

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!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.