October 24, 201213 yr Hi everyone. My aim here is to have a database I have in MySQL write to a csv file when the person visits a link via PHP. So they visit the link -> then the PHP calls the data from MySQL -> that is the written to an array -> which is used to create the csv cells. I have the below so far after reading documentation on PHP.net $query = mysql_query("SELECT * FROM my_table", $connection); $list = array ( while ($row = mysql_fetch_array($query)) { array(.$row['first-name']., .$row['last-name']., .$row['email'].), } array('end', 'end', 'end') ); $fp = fopen('file.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); I know the above will not work, but i cant seem to figure out how to work around this using the "while" loop to call all the data. Anyone who can shine some light on a work around would be much appreciated. Thanks in advance.
October 24, 201213 yr You can use array_push to put the query results into your array. Something like $r = mysqli_query($connection, "SELECT * FROM my_table"); $list = array (); $eof = array('end', 'end', 'end'); while ($row = mysqli_fetch_row($r)) { array_push($list, $row); } array_push($list, $eof); $fp = fopen('file.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); I've used the mysqli extension which has superceded mysql. You'll need to be using PHP version 5 and MySql version 4 (I think) to use the newer mysqli extension.
October 24, 201213 yr Author thanks for the reply, that makes more sense to use array push! although i have tested your method and its only writing "end end end" to my file. So i tried doing: while ($row = mysql_fetch_row($r)) { array_push($list, $row[0]); array_push($list, $row[1]); array_push($list, $row[2]); array_push($list, $row[3]); } But no luck either, im still trying to look at the problem so will let you know if i find out what it is. Dont suppose you have any further ideas?
October 24, 201213 yr You might want to check that your query is working, while ($row = mysqli_fetch_row($r)) { print_r($row); array_push($list, $row); }
October 26, 201213 yr Author thanks, your code actually did work, it was just me trying to call data from a table name with a typo in it ha. Thanks for your help
Create an account or sign in to comment