Exporting data from database to csv file using php - php

I am able to export database to csv but my code somehow imports twice the data to my csv file. I.e same column twice side by side.this is my code. I think my problem is with the implode statment. Any help would be appreciated.
<?php
$db = new sqlite3('I:\preethi\webbs.db');
$headers = array
('Id','CompanyId','DateTime','Serial','DeviceId','AgentAId','GpsAddress','Targa','CommonRoadDescription'
,'RoadCivicNumber','VehicleBrandDescription','VehicleModelDescription' ,'VerbaliVehicleTypeDescription','CommonColorVehicleDescription','VerbaliRuleOneCode','VerbaliRuleOneDes
cription','VerbaliRuleOnePoints'
,'VerbaliClosedNoteDescription','Points','VerbaliMissedNotificationDescription
','MissedNotificationNote','StatementNote');
$results = $db->query('select'.implode (',',$headers).'from VerbaliData');
//$results = $db->query( 'select
Id ,CompanyId ,DateTime ,Serial ,DeviceId ,AgentAId
,GpsAddress ,Targa ,CommonRoadDescription ,RoadCivicNumber ,VehicleBrandDescription
,VehicleModelDescription ,VerbaliVehicleTypeDescription ,CommonColorVehicleDescription
,VerbaliRuleOneCode ,VerbaliRuleOneDescription ,VerbaliRuleOnePoints ,VerbaliClosedNoteDescription
,Points ,VerbaliMissedNotificationDescription ,MissedNotificationNote ,StatementNote from
VerbaliData');
$fp = fopen('explores.csv', 'w');
fputcsv($fp,$headers);
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);
?>

Just try with :
while($row = $results->fetchArray(SQLITE3_NUM)) {
Or
while($row = $results->fetchArray(SQLITE3_ASSOC)) {
More Details: http://php.net/manual/en/sqlite3result.fetcharray.php

You have a slight prob in your code fetchArray() returns two array sets one associative and one is numbered, use fetchArray(SQLITE3_NUM) or fetchArray(SQLITE3_ASSOC).

Related

Read csv file and update the mysql table with php code

I have a csv file downloaded from ftp server with curl and now i need to update the datas in mysql table based on the guid field in csv. Can anyone please help me on this?
Datas of csv file:
GUIDcsvinterest_amyloidosiscsvinterest_ahuscsvinterest_complement_mediated_diseasescsvinterest_hemophiliacsvinterest_hyperoxaluriacsvinterest_PNHcsvinterest_porphyriascsvdouble_opt_in_datecsvopt_outcsvdate_addedcsvdate_modified
X1000csvFalsecsvFalsecsvFalsecsvFalsecsvFalsecsvFalsecsvFalsecsv2018-02-01 13:21:00csv2018-02-21 09:00:00csv2017-02-01 13:00:00csv2018-02-21 09:00:00
First 3 lines are field names of the table and last 2 lines are the values that needs to be updated.
Tried this so far:
$csvFile = 'csv/filecurl.csv';
$rows = array_map('str_getcsv', file($csvFile));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = $row;
}
echo '<pre>';
print_r($csv);
echo '</pre>';

Generating 2-dimension array in PHP with SQL query

looking for generating a multi-dimensional array in php (2 for now, more later) with SQL query results, in order to push it in a CSV file later. I want each line "each member" to contain 2 rows, "name" and "surname".
I'm trying this:
$table_echo ="";
$sql='SELECT * FROM members;
$nb = $bdd->query($sql);
while($result = $nb->fetch()){
$table_echo.= array($result['name'],$result['surname']).",";
}
$data = array(
$table_echo
);
inspired from the following example (w3schools.com):
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
SQL is OK, so do the CSV file generator (tested and working with the $cars array example), but the output CSV file is empty with the first code. What am I getting wrong? Can I use a "while" inside the $data array definition ? Is there an other way to do this? Thanks
I will use variables from the car example for better understanding
$cars = array();
// ... sql
while($result = $nb->fetch()){
$cars[] = array($result['name'],$result['surname']);
}
// here you have $cars full of data in "correct" structure
this should build the same structure as the cars example
You do not need to create array if your purpose only is to save a file as CSV.
//open csv file - if not exists will create new file
$csv_file = fopen('output.csv', "w");
$sql='SELECT * FROM members';
$nb = $bdd->query($sql);
while($result = $nb->fetch()){
//prepare line
$line = $result['name'].",".$result['surname'])."\n";
//write line to csv file
fwrite($csv_file, $line);
}
fclose($csv_file);
You can do this way
$table_echo ="";
$sql='SELECT * FROM members';
$nb = $bdd->query($sql);
$data = [];
while($result = $nb->fetch()){
$data []= array($result['name'],$result['surname']);
}

How to add an entry to mysqli array

I am trying to add a single column at the beginning of a csv file using the code below:
while ($row = mysqli_fetch_array($rows, MYSQL_ASSOC)) {
$list = "'2795', $row";
fputcsv($output, $list);
}
What am I missing? I know it's something simple. Thank you in advance.
You can't just join those values together:
$list = "'2795', $row";
Since $row returns a row result array, treat it as such, push that value inside:
$output = fopen('whatevername.csv', 'a+');
while ($row = mysqli_fetch_array($rows, MYSQLI_ASSOC)) {
$row[] = '2795'; // `$row` is an associative array
fputcsv($output, $row);
}
fclose($output);
Sidenote: This is a truncated code, so just make sure you have that file handle above this code that you presented.

PHP Export to CSV [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP Export Excel to specific Path?
I'm not really familiar with PHP exporting to excel or csv, but I'm using PHP MySQL for a local point of sale.
According to the code below, this actually works..But not in the way it should be ! All records are placed as 1 row inside the csv file, how can i fix that ? Also, How would I stop overwriting the same file...I mean When I click on a Button to export the csv, it should check if there is an existing csv file, If there is--Create new one !
Thank You
require_once('connect_db.php');
$items_array = array();
$result = mysql_query("SELECT * FROM sold_items");
while($row = mysql_fetch_array($result))
{
$items_array[] = $row['item_no'];
$items_array[] = $row['qty'];
}
$f = fopen('C:/mycsv.csv', 'w');
fputcsv($f, $items_array);
fclose($f);
fputcsv appears to only be writing one row/record, and includes a row/record terminator in its output. You will need to call fputcsv for each line of the report.
dbf's solution for a sequential filenaming works well in many cases. Personally, I've found appending a timestamp helpful, as it requires less IO when there is a collection of existing files. Additionally, it makes it possible to know when the report was from without having to open each, even in the cases where the report was modified/copied/touched.
Minor detail: adjusted the query to just the columns your using.
<?php
require_once('connect_db.php');
$result = mysql_query("SELECT item_no, qty FROM sold_items");
$timestamp = date('Ymd-His');
$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers
fputcsv($f, array('Item No', 'Qty'));
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}
fclose($f);
First of all
$items_array[] = array($row['item_no'], $row['qty']);
second, use a variable to store the files name.
$filename = $name = "myscsv";
$index = 1;
while(file_exists($filename.".csv")) {
$filename = $name.$index;
$index++;
}
now you can save it ;)
$f = fopen("C:/{$filename}.csv", 'w');

Writing a Database Query to a file

I am trying to write a Database Query to a file, But am just wondering how I get the SQL Data to be input into the file.
It is currently outputting nothing to the .txt file at all. I suspect its something to do with the while loop and am questioning whether it needs to be there or not.
My code is :
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
$query = "SELECT gamename, username, MAX(thescore)
FROM game_scores
GROUP BY gamename, username
ORDER BY gamename, thescore DESC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$scoredata = $row;
}
//save file
$handle = fopen('scores/games-backup'.'.txt','w+');
fwrite($handle,$scoredate);
fclose($handle);
echo "Success";
}
Any help on writing the SQL Results to this text file would be much appreciated.
$row is an array, you will need to make it a string before you can write it to a file, you can use implode().
$scoredata is also being overwritten in each loop, maybe use $scoredata[] instead
while($row = mysql_fetch_array($result)) {
$scoredata[] = implode("; ", $row);
}
This will make $scoredata an array also, so you will need to convert that to a string too!
$handle = fopen('scores/games-backup'.'.txt','w+');
fwrite($handle,implode("\r\n", $scoredata));
fclose($handle);
This should print each database row on a new line in the file.
EDIT: This will just be a text file, formatted as text, not that great for a backup file. You will need to structure the text into an SQL format to make it useful..
Try something like :
$handle = fopen('scores/games-backup'.'.txt','w+');
while($row = mysql_fetch_array($result)) {
fputs($handle, join(';', $row)."\n");
}
fclose($handle);
$row is an array, you must join it (or access the elements )
$row is not a string, you have to make it a string before you can put it into a file.
And you have to change $scoredata to $scoredata[] because, it is now being overwritten continiously.
You can use print_r function with second parameter set true.
$str = print_r($row, true);
fwrite($handle,implode("\r\n", $str));
Or you can serialize the array
$str = serialize($row);
fwrite($handle,implode("\r\n", $str));

Categories