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);
Related
I have a PHP page that select record from my SQL table and send an encrypted version of the record to CSV file. My problem is: when I select the record without using openssl encrypted, it export sucessfully, However, if I include the encrypte it opens a blank screen.
i hope will get a help here. Many Thanks in advance
This is my code:
<?php
// Database Connection
require("xxx.php");
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'))
$encryption_key = 'bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU=';
$result='select *
from encrypt';
$file='grade/file'.date('YmdDH_i_s').'.csv';
$qry = "select * from gb_centre where use_flag=1";
$rs = mysqli_query($con,$qry);
$getRowAssoc = mysqli_fetch_assoc($rs);
$query = (
openssl_encrypt($result->uniqueid,'AES-256-CBC',$encryption_key,0,$iv),
openssl_encrypt($result->username,'AES-256-CBC',$encryption_key,0,$iv),
openssl_encrypt($result->shortname,'AES-256-CBC',$encryption_key,0,$iv),
openssl_encrypt($result->rawgrade,'AES-256-CBC',$encryption_key,0,$iv),
openssl_encrypt($result->finalgrade,'AES-256-CBC',$encryption_key,0,$iv),
openssl_encrypt($result->cid,'AES-256-CBC',$encryption_key,0,$iv),
openssl_encrypt($result->id,'AES-256-CBC',$encryption_key,0,$iv)
);
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}
$users = array($uniqueid,$username,$shortname,$rawgrade,$finalgrade,$cid,$id);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$users[] = $row;
}
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$getRowAssoc['cid'].date('_Y-m-d_Hi').'.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('a1', 'a2', 'a3', 'a4', 'a5','a6','a7'));
if (count($users) > 0) {
foreach ($users as $row) {
fputcsv($output, $row);
}
}
?>
**
EDIT:
**
I have edited the section of the code, it can now export the record to csv using the PHP OpenSSL and works fine, The problem is, it adds extra columns in the CSV file. I can't figure out where the error is.
Here is the edited code:
<?php
// Database Connection
require("config.php");
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$key = 'bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU=';
$encryption_key = 'bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU=';
$string='select *
from encrypt'
$qry = "select * from gb_centre where use_flag=1";
$rs = mysqli_query($con,$qry);
$getRowAssoc = mysqli_fetch_assoc($rs);
if (!$result = mysqli_query($con, $string)) {
exit(mysqli_error($con));
}
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$uniqueid[] = openssl_encrypt($row->uniqueid,'AES-256-CBC',$encryption_key,0,$iv);
$username[] = openssl_encrypt($row->username,'AES-256-CBC',$encryption_key,0,$iv);
$shortname[] = openssl_encrypt($row->shortname,'AES-256-CBC',$encryption_key,0,$iv);
$rawgrade[] = openssl_encrypt($row->rawgrade,'AES-256-CBC',$encryption_key,0,$iv);
$finalgrade[] = openssl_encrypt($row->finalgrade,'AES-256-CBC',$encryption_key,0,$iv);
$cid[] = openssl_encrypt($row->cid,'AES-256-CBC',$encryption_key,0,$iv);
$id[] = openssl_encrypt($row->id,'AES-256-CBC',$encryption_key,0,$iv);
}
}
$users = array($uniqueid,$username,$shortname,$rawgrade,$finalgrade,$cid,$i);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$getRowAssoc['cid'].date('_Y-m-d_Hi').'.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('a1', 'a2', 'a3', 'a4', 'a5','a6','a7'));
if (count($users) > 0) {
foreach ($users as $row1) {
fputcsv($output, $row1);
}
}
?>
It looks like you are having a hard time with the fundamentals of executing queries. I would just write some simple code to fetch and show the results of a single query. Then when you get the idea you can add more to your code.
This is an example using prepared statements. This will prevent sql injections. You should learn how to use prepared statements for all of your queries going forward. Here is a link to a good resource that will teach you how to do any query you need to do properly. Bookmark this link and refer to it often. MySQLi Prepared Statements
This code will print out the uniqueid from each row of the results returned from your query.
$query = "SELECT *
FROM gb_centre
WHERE use_flag = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('i', 1); //set your bindings
$stmt->execute();
while ($result = $stmt->fetch_object()) {
echo $result->uniqueid . '<br>';
}
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);
I am trying to export data from PhpMyAdmin to JSON format
This code works for select lat,lng from googlemaps, but does not for the address column
My code is:
<?php
$con=mysqli_connect("localhost","root","","googlemaps");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT lat,lng,`addr` FROM infos";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row =mysqli_fetch_array($result))
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
$fp = fopen('results01.json', 'w');
fwrite($fp, "{ \"tab\": ");
fwrite($fp, json_encode($resultArray));
fwrite($fp, " }");
fclose($fp);
echo json_encode($resultArray);
//var_dump($resultArray);
?>
Screenshot of infos table:
Just found the solution it s actually adding this before the select query :
mysqli_set_charset($con, "utf8");
$sql = "SELECT lat,lng,`addr` FROM infos";
if ($result = mysqli_query($con, $sql))
{......}
So I want to export a JSON file from a MySQL database table, a php script that runs weekly and exports JSON file from a specific table.
This is sort of the thing I want to achieve:
<?php
$json_file_name = "File_export.json";
$json_file_name = str_replace(" ", "_", $json_file_name);
$con = mysqli_connect("", "", "", "");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date_range = array(
"start" => date("Y-m-d H:i:s", strtotime("-7 days")),
"end" => date("Y-m-d H:i:s", strtotime("now")),
);
and so on
if(!empty($json_data) && count($json_data) > 1)
{
$json_file_data = "";
$fp = fopen($json_file_name, 'w');
foreach($json_data as $row)
{
$json_file_data .= implode(",", $row) . "\n";
}
fwrite($fp, $json_file_data);
fclose($fp);
What is the best way to achieve the same.
Thank you :)
If your database table not too large, you can fetch all rows into a single array, then turn that array into JSON automatically without looping. This will generate JSON with column values as a list:
// $con is connection, $json_filename is name of filename to write
$query = "select * from MyTable";
// Fetch all rows into $json_data array
$result = mysqli_query($con, $query);
$json_data = mysqli_fetch_all($result);
mysqli_close($con);
// Turn data into JSON and write to file
$json = json_encode($json_data);
file_put_contents($json_filename, $json);
Example output:
[["name1","address1"],["name2","address2"]]
If your database table is a little bigger, it is better to write each line as it is generated. The code below will create a JSON object for each row.
$query = "select * from MyTable";
$result = mysqli_query($con, $query);
// Open output file
$fp = fopen($json_file_name, 'w');
// Write JSON list start
fwrite($fp, '[');
// Write each object as a row
$isFirstRow = true;
while ($row = mysqli_fetch_assoc($result)) {
if (!$isFirstRow) {
fwrite($fp, ',');
} else {
$isFirstRow = false;
}
fwrite($fp, json_encode($row));
}
// Write JSON list end
fwrite($fp, ']');
// Close file and MySQL connection
fclose($fp);
mysqli_close($con);
Example output:
[{"name": "name1", "address": "address1"},{"name": "name2", "address": "address2"}]
I think you also want to change this line:
$json_file_data .= implode(",", $row) . "\n";
to this:
$json_file_data[] = implode(",", $row);
Which will cause this:
$json = json_encode($json_data);
To deliver a json array of your database rows.
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;
}
}