Jump to content

Add Column and Value existing CSV


eugenevz

Recommended Posts

Hi

 

I have a script which picks up CSV files and inserts into a table (mysql).

 

I am a beginner and finding it difficult to get the script to add an additional column to existing CSV, and add value to column, for each row...

 

Here is the script.... 

How can I manipulate $csv and add a column (including separator) and value ($filedate) for each row?  Help much appreciated.

 

for example:

 

CSV contains:

Number, Name, LastName

1, John, Thomas

2, Jeffrey, James

 

I need to add:

Number, Name, LastName, Date

1, John, Thomas, 2014-10-31

2, Jeffrey, James, 2014-10-31



<?php


#! /usr/bin/env php
$databasehost = "localhost"; 
$databasename = "****"; 
$databasetable = "****"; 
$databaseusername="****"; 
$databasepassword = "****"; 
$fieldseparator = ","; 
$lineseparator = "\n";
$files = glob("*ETF_*.csv");
$filedate = "2014-10-31";


if (empty($files)) {
    die("No records were loaded.");
}
else 
foreach($files as $csv)
$etf_array = array(
            PDO::MYSQL_ATTR_LOCAL_INFILE => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
{
try {
    $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", 
        $databaseusername, $databasepassword, $etf_array   
    );

catch (PDOException $e) {
    die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
      LOAD DATA LOCAL INFILE ".$pdo->quote($csv)." INTO TABLE `$databasetable`
      FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
      LINES TERMINATED BY ".$pdo->quote($lineseparator)."
      IGNORE 1 LINES");


echo "Daily - Loaded a total of $affectedRows records from $csv.\n"; 
}
?>

Link to comment
https://forums.phpfreaks.com/topic/292186-add-column-and-value-existing-csv/
Share on other sites

I assume you only want to add todays date to the database and not the csv file aswell?

 

Add the following to the end of your query

 SET date_column = CURRENT_DATE()

change date_column to the actual name of your column you want to add the date to

 

NOTE When posting code please wrap it within


tags (or click the <> button in the editor)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.