I'm having a mysqli result set written to a CSV file in PHP using the following code
$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);
}
which, from what I understand, should produce a comma separted line for each row.
However, the contents of the CSV file consists of one long string without linebreaks.
Any idea how to get a linebreak for each row?
Thanks.
fclose($fp);
You need to loop until last record and add each record in csv. change your code as:
$result = mysqli_query($con, 'SELECT * FROM table');
$fp = fopen('file.csv', 'w');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
fputcsv($fp, $row);
}
fclose($fp);
Related
I think I used fputcsv correctly.My database table contains two columns with dates and numbers in both columns. I use an oracle database and a windows 2008 server.
//Connexion BDD Oracle
$connect = odbc_connect("oraclesrc", "xe", "sec123");
$query = "select * from timedata";
$result = odbc_exec($connect, $query);
$numOF = 0;
while(odbc_fetch_row($result)) {
$emp = odbc_result($result, 1);
$time = odbc_result($result, 2);
$numOF++;
echo $emp;
echo $time;
}
$fp = fopen('testfile.csv', 'w');
foreach ($row as $result) {
fputcsv($fp, $result);
}
fclose($fp);
odbc_close($connect);
The while loop fetches the result rows one at a time. If you change to use odbc_fetch_array($result) you will get an Assoc array exactly as fputcsv() want to see it.
//Connexion BDD Oracle
$connect = odbc_connect("oraclesrc", "xe", "sec123");
$query = "select * from timedata";
$result = odbc_exec($connect, $query);
$fp = fopen('testfile.csv', 'w');
while($row = odbc_fetch_array($result)) {
fputcsv($fp, $row);
}
fclose($fp);
odbc_close($connect);
I'm trying to export my data into a CSV in PHP after running some queries on it. So far, I'm able to successfully to do so using:
$temp = mysqli_query($link, $sql);
$fp = fopen("results.csv", "w");
while($row = mysqli_fetch_array($temp, MYSQLI_ASSOC)){
fputcsv($fp, $row);
}
fclose($fp);
However, I don't understand how to keep the headers that my SQL query forms.
The basics is, just insert the first row as your headers manually
$temp = mysqli_query($link, $sql);
$fp = fopen("results.csv", "w");
fputcsv($fp, array("Header 1", "Header 2", "Header 3");
while($row = mysqli_fetch_array($temp, MYSQLI_ASSOC)){
fputcsv($fp, $row);
}
fclose($fp);
Untested, but something like this:
$added_headers = false;
while($row = mysqli_fetch_array($temp, MYSQLI_ASSOC)){
if(!$added_headers) {
fputcsv($fp, array_map(function($field) {return $field->name;}, mysqli_fetch_fields($temp)));
$added_headers = true;
}
fputcsv($fp, $row);
}
First get the query columns as headers. Put them to csv once before putting the data.
$flag = 0; // define a flag to check if header is printed to csv file
while($row = mysqli_fetch_array($temp, MYSQLI_ASSOC)){
if(!flag){ // if header is not added
$header = array_keys($row);
fputcsv($fp, $header); // add header to csv file
$flag = 1; // update the flag
}
fputcsv($fp, $row);
}
Not tested but at least it gives some idea.
I have a MySQL column that holds a JSON string of question numbers (0-165) as a key and question answers (score of 1-5) as a value. I need to retrieve all of the MySQL columns, put them into a .csv file with the JSON values in separate columns.
So far, I have a working PHP function that outputs the entirety of my MySQL table to an CSV file using fputcsv(). Here is the code:
function buildcsv(){
$start = $_POST['start'];
$end = $_POST['end'];
$result = mysql_query('SELECT fullname, institution, email, timestamp, responsesJSON
FROM `members` WHERE timestamp BETWEEN "'.$start.'" AND "'.$end.'"');
if (!$result) die('Couldn\'t fetch records');
ob_start();
$fp = fopen('php://output', 'w');
if ($fp && $result) {
while ($row = mysql_fetch_row($result)) {
fputcsv($fp, array_values($row));
}
fclose($fp);
return ob_get_clean();
}else{
$error = "Error. Either there is no data or invalid date.";
return $error;
}
}
And here is the output from the code:
However, I need my CSV output to resemble the following mockup:
Is it possible to do this without changing my database structure? I have seen code on stackoverflow that puts JSON values into separate columns, but how would I integrate it into my existing code which retrieves all other MySQL columns?
Thank you all in advance.
Try this way
while ($row = mysql_fetch_row($result)) {
$marks = json_decode($row['responsesJSON'],true);
unset($row['responsesJSON']);
fputcsv($fp, array_merge(array_values($row),array_values($marks)));
}
That is not best solution, but just food for thought and point to start.
Hope it could help
Much thanks to #KimAlexander and #RocketHazmat's suggestions, I figured it out:
function buildcsv(){
$start = $_POST['start'];
$end = $_POST['end'];
$result = mysql_query('SELECT fullname, institution, email, timestamp, responsesJSON
FROM `members` WHERE timestamp BETWEEN "'.$start.'" AND "'.$end.'"');
if (!$result) die('Couldn\'t fetch records');
ob_start();
$fp = fopen('php://output', 'a');
if ($fp && $result) {
while ($row = mysql_fetch_assoc($result)) {
$personal = array($row['fullname'], $row['institution'], $row['email'], $row['timestamp']);
$scores = json_decode($row['responsesJSON'], true);
fputcsv($fp, array_merge($personal, $scores));
}
fclose($fp);
return ob_get_clean();
}else{
$error = "Error. Either there is no data or invalid date.";
return $error;
}
}
I have some code here that exports to a csv file. I connected to the database and saw that there was well over 30 entries or so. But I'm only getting one in the csv file. The top part gets the headings for the file and the bottom the values, the values array is only returning one array and putting it into the file. I'm not sure what's causing this issue. Anny suggestions would be greatly appreciated.
<?php
$FileName = "mro_export_".date("Y-m-d_H-i",time()).".csv";
$file = fopen($FileName,"w");
$sql = mysql_query("SELECT * FROM `$table` LIMIT 11");
$row = mysql_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
$ValuesArray=array();
foreach($row as $name => $value){
$ValuesArray[]=$value;
}
fputcsv($file,$ValuesArray);
fclose($file);
header("Location: $FileName");
?>
You need to call mysql_fetch_assoc in a loop to get all the rows.
<?php
$FileName = "mro_export_".date("Y-m-d_H-i",time()).".csv";
$file = fopen($FileName,"w");
$sql = mysql_query("SELECT * FROM `$table` LIMIT 11") or die(mysql_error());
$first_line = true;
while ($row = mysql_fetch_assoc($sql)) {
if ($first_line) {
// Save headings alon
fputcsv($file, array_keys($row));
$first_line = false;
}
fputcsv($file, array_values($row));
}
fclose($file);
header("Location: $FileName");
?>
I have been dealing with this all day ... I am doing a SQL Query and it suppose to return several rows, but I am only getting one, I would believe it is the first one, I want to save these results/rows in a CSV file.
So when I do the var_dump only one result is showing and I can only write that first line in the CSV file.
session_start();
$file = 'file.csv';
if(isset($_POST['button1'])){
echo("You clicked button one!");
$con=mysqli_connect("localhost","root","","test");
$query = "SELECT * FROM test.tec_milenio_cubo";
$result = mysqli_query($con, $query); // EJECUTAS LA CONSULTA
$row = mysqli_fetch_assoc($result);
var_dump ($row);
$_SESSION['file'] = $file;
$fp = fopen($file, 'w');
foreach ($row as $value) {
fputcsv($fp, $value);
}
fclose($fp);
mysqli_close($con);
Use a while loop on your $row.
$fp = fopen($file, 'w');
while ($row = mysql_fetch_array($result)) {
var_dump ($row);
fputcsv($fp, $row);
}
fclose($fp);
Quixrick is correct.
Your initial code is only pulling one record from the database at a time.
The while loop will continue until all records are pulled and end when $row is not assigned a value.
Happy Coding :-)!