synking Posted August 22, 2012 Share Posted August 22, 2012 Hey guys, So i recently was trying to get mysql generated csv file.... found that to hard to get right through pdo. So what i did instead is had php parse the data and use fputcsv but it's not working for me quite right thought i would see what im doing wrong. <?php include('inc/dbconnect.php'); $filename = 'Innovation_data.csv'; try { $dbh = new pdo("mysql:host=$serv;dbname=$data", $name, $pass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT * FROM Customer_Card"; $sth = $dbh->prepare($sql); $sth->execute(); $filename = "/var/www/html/innovation/inc/crad".time().".csv"; $handle = fopen($filename, 'w+'); foreach($sth->fetch(PDO::FETCH_ASSOC) as $row => $value) { fputcsv($handle, array($row, $value)); } fclose($handle); $dbh=null; } catch(PDOException $e) { echo ("I'm sorry, Dave. I'm afraid I can't do that."); error_log($e->getMessage()); } header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Length: ". filesize("$filename").";"); header("Content-Disposition: attachment; filename=$filename"); header("Content-Type: application/octet-stream; "); header("Content-Transfer-Encoding: binary"); readfile($filename); ?> I get the file created and downloaded but when i open it it's only the first line of the mysql table. And the name of the file is the whole sting /var/ww.... which i could correct by just fixing the string but i am just confused as why it's not writing the enitre table to the database. Link to comment https://forums.phpfreaks.com/topic/267425-mysql-putcsv-issue/ Share on other sites More sharing options...
xyph Posted August 22, 2012 Share Posted August 22, 2012 Foreach doesn't work this way. $sth->fetch(PDO::FETCH_ASSOC) will only be executed once. You want to use a while loop. Link to comment https://forums.phpfreaks.com/topic/267425-mysql-putcsv-issue/#findComment-1371448 Share on other sites More sharing options...
synking Posted August 22, 2012 Author Share Posted August 22, 2012 Ahh i thought that it would step through thanks guess i just was not thinking. Link to comment https://forums.phpfreaks.com/topic/267425-mysql-putcsv-issue/#findComment-1371449 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.