I have myssql db with different tables. The data between the tables are linked and I retrieve and display them by using the userid. I used the reference from PHP MYSQLi Displaying all tables in a database
But how do I export this information as a csv file? I have tried instead of echo changed it to a string and print the string to a csv file but it is not working.
But I can see the data but on top there is also junk (like "
etc) inside the csv file.
Is there another way to do this?
解决方案
If you want to write each MySQL row to a CSV file, you could use the built in PHP5 function fputcsv
$result = mysqli_query($con, 'SELECT * FROM table');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$fp = fopen('file.csv', 'w');
foreach ($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);
Which should return a comma separated string for each row written to file.csv:
row1 val1, row1 val2
row2 val1, row2 val2
etc..
Also be sure to check permissions for the directory you are writing to.