PHP - fputcsv: put JSON values retrieved from MySQL field in separate columns - php

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

Related

Cannot write to my csv file from Oracle database using PHP

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

Object of class DateTime error when i export data to excel

I have a table which contain many columns. Some column contain numerical value, some contain text while some contain date.
When i try to export data to Excel, the numerical and value can be exported however when i want to export date data, it shows me this error "Object of class DateTime could not be converted to string".
My export function works in such a way that user can select which column they wan to export from SQL to excel through PHP. My column are stored in array. Below is my code:
//Get list of selected column from selected checkboxes
$colarray = $_GET['colarray'];
//convert string to array
$string1 = ['[',']'];
$string2 = ["",""];
$newcolarray = str_replace($string1, $string2, $colarray);
$newarray = explode(",",$newcolarray);
$filename = "File name " . date('d-M-y') . ".csv"; // Create file name
$f = fopen('php://memory', 'w');
//Insert column name in first row of excel
fputcsv($f, $newarray);
//dynamic Select query statement
$query = "SELECT ";
$query .= $colarray;
$query .= " FROM OVERALL_SUMMARY_ORIGINAL"; // Get data from Database from OVERALL_SUMMARY_ORIGINAL table
$stmt = sqlsrv_query($conn, $query);
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
/**how can i place this code $row['Date']->format('d M Y') here***/
fputcsv($f, $row);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
Can anyone help how i can convert my date data into a string since my columns are stored in array for exporting to csv?
With PHP Driver for SQL Server you may retrieve PHP Date and Time objects as strings or as DateTime objects using the 'ReturnDatesAsStrings' option in the connection string or at the statement level.
If I understand your case correctly, the columns in the SQL statement are dynamic. In this case you may try to use this feature at the statement level.
<?php
...
$query = "SELECT ";
$query .= $colarray;
$query .= " FROM OVERALL_SUMMARY_ORIGINAL"; // Get data from Database from OVERALL_SUMMARY_ORIGINAL table
$options = array('ReturnDatesAsStrings' => true);
$stmt = sqlsrv_query($conn, $query, array(), $options);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
fputcsv($f, $row);
}
...
?>
Another option, of course, is to format the PHP DateTime object using DateTime::format method, but after you check that these values are PHP DateTime objects.
<?php
...
$query = "SELECT ";
$query .= $colarray;
$query .= " FROM OVERALL_SUMMARY_ORIGINAL"; // Get data from Database from OVERALL_SUMMARY_ORIGINAL table
$stmt = sqlsrv_query($conn, $query);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
foreach($row as $key => $value) {
if ($value instanceof DateTime) {
$row[$key] = $row[$key]->format('d M Y')
}
}
fputcsv($f, $row);
}
...
?>

using fputcsv is only returning one row of data to export

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

Getting only 1 Result from a Query - Saving Result in a CSV File

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 :-)!

Save a query as CSV file, but can't get table header field names to write in CSV

I'm successfully creating a CSV file from a query and saving the file on the server, but I can not get the csv to contain the header fields, per the query column names. I am creating a headers array from the mysql_field_name, but can't get it to write the headers to the csv, it only writes the table data. Any thoughts / examples greatly appreciated.
//Create a CSV for
$result = mysql_query("SELECT * FROM `car_details`");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$csv_filename = "Policy-" .$datetime.".csv";
$fp = fopen($csv_filename, 'w+');
if ($fp && $result)
{
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
Would look like:
...
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
Try writing $headers to the file as the first line.

Categories