Read csv file and update the mysql table with php code - php

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

Related

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.

How to write mysql table data to an excel file but no downlad just store the file

I want to send the xls file as an attachment.
For that I need to store the xls file at some location and then send it as attachment.
The xls file data is basically fetched from a mysql table.
Just write mysql query results to csv file format. It's xls compatible.
$result = mysqli_query($con, 'SELECT * FROM table');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$fp = fopen('/tmp/file.csv', 'w');
foreach ($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);

Exporting data from database to csv file using 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).

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

Reading a txt file in php and parsing the data to MySQL

im new to php and i hope you can help with an easy to get script. I have a txt file with this general format:
5TB-2A, L+, 1, 1695, 3255, l.jpg
5TB-2A, L-, 2, 1965, 3270, l.jpg
5TB-2A, D-, 7, 2970, 3270, l.jpg
5TB-2A, DFOK, 8, 3225, 3300, l.jpg
I want to read this txt file using php to retrive every data separated by "," into my MySQL table. Thanks for any help.
$lines=file($yourTxt);
foreach($lines as $v) {
$values = explode(',',$v);
PDO::prepare("INSERT INTO tbl (?,?,?,?,?)");
PDO::execute($values);
}
You can make a further check too see if the line just read is ok like:
foreach($lines as $v) {
$values = explode(',',$v);
if (count($values)!=6)
continue;
}
You could use fgetcsv (http://php.net/fgetcsv) to read the file into an array in PHP and then write a query to insert it into the table one row at a time.
<?php
$results = array();
$rows = file($filename, FILE_SKIP_EMPTY_LINES);
if(empty($rows)){
// no data to parse
} else{
foreach($rows as $row){
$values = explode(', ', $row);
// keep only those values which have the 5 variables
if(count($values) > 5){
$results[] = $values;
}
}
}
// see if we have the correct data
print_r($results);
// ... then do your db inserts here
?>

Categories