Importing CSV data into MySQL table - php

I have a CSV file which contains data seperated with tabs. I need to import the data into a MySQL table which consists of two columns. The first CSV column should go into the first column of the table and similarly for the second.
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("translation",$con);
$open=fopen("EH_excel.txt","r");
while(($get=fgetcsv($open,1000,","))!==false) {
mysql_query("insert into dictionary(english,croatian)
values('".$get[0]."','".$get[1]."')");
}
fclose($open); echo "Import Done.";
?>
Can anybody help me?

Since what you have is called Tab Delimited Files
This is the way you import it to
SQL
LOAD DATA LOCAL INFILE 'sample.txt' INTO TABLE sample
FIELDS TERMINATED BY '\t'
OPTIONALLY ENCLOSED BY ''
ESCAPED BY ''
LINES TERMINATED BY '\n';

Related

PHP MySQL LOAD DATA - exclude duplicates

Currently I'm using the following to import a CSV file in to a table.
$query = <<<eof
LOAD DATA LOCAL INFILE 'list.csv'
INTO TABLE pupils
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
( -- Field List -- )
eof;
if ($conn->query($query) === TRUE) {
echo "Data Imported successfully";
} else {
echo "Error importing data: " . $conn->error;
}
-- Field List -- is a comma separated list of fields.
This works well and imports the data from the CSV file in to the table.
I've got a new CSV to import and there are going to be some entries that already exist in the database. During the import is it possible to check if a entry already exists ?
My Database has a field called remote ip which will be unique for each entry. Is there anyway to check if it exists and it it does don't import that row from the CSV ?
Thanks
No. LOAD DATA INFILE does exactly what it says. You will have to remove the duplicates separately.

PHP - Rows are not in proper format after importing csv to mysql using LOAD INTO INFILE

I'm new here. I would like to ask question regarding with my codes. So my code is working perfectly but then after importing csv to mysql programmatically using LOAD INTO INFILE. I didn't know why my output kept getting this kind of format. Please see my codes below thanks!
$testing = $conn->prepare("LOAD DATA INFILE 'C:/xampp/mysql/data/mysql/usagetable.csv'
INTO TABLE trieinitialcountentry
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(Count_ID, InvItemLocID, OnHand, OnHandValue, StockCenter_ID)");
$testing->execute();
And also, some rows had been imported perfectly but some of them are not. Example of my output:
Count_ID InvItemLocID OnHand OnHandValue StockCenter_ID
737450 -2091889269 140.00 "2 788.80"
Apparently some of the values in the input CSV file are wrapped in quotes and you didn't pass this information to LOAD DATA INFILE.
Try this query:
$query = <<<'END'
LOAD DATA INFILE 'C:/xampp/mysql/data/mysql/usagetable.csv'
INTO TABLE trieinitialcountentry
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(Count_ID, InvItemLocID, OnHand, OnHandValue, StockCenter_ID)
END;
$testing = $conn->prepare($query);
$testing->execute();
Note the added OPTIONALLY ENCLOSED BY '"' clause.

Building an application to transform CSV files

I have a rough and complete working CSV transformer. The way my current system works is it imports the CSV file into an SQL database table with static column names, and exports only specific (needed) columns. This system works great but is only specific to one type of CSV file (because the column names are pre-defined.) I'm wondering how I can make this universal. Instead of having it insert column1, column2, column3. I want to insert Spreadsheet Column1, Spreadsheet Column2, Spreadsheet Column3, etc. How would I go about pulling the column names from the CSV file, and creating a new table in the database with the column names being those from the first row of the CSV file.
The current system:
Client uploads CSV file.
A table is created with predefined column names (column 1, column 2, column 3)
Using LOAD DATA INFILE -> PHP scripts will insert the information from the CSV file into the recently created table.
The next query that is ran is simply something along the lines of taking only specific columns out of the table and exporting it to a final CSV file.
The system that would be ideal:
Client uploads CSV file.
PHP scripts read the CSV file and takes only the first row (column names), after taking these column names, it'll create a new table based on the column names.
PHP scripts now use LOAD DATA INFILE.
The rest is the same as current system.
Current code:
import.php
include("/inc/database.php");
include("/inc/functions.php");
include("/inc/data.php");
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$string = random_string(7);
$new_file_name = 'report_'. $string .'.csv';
$themove = move_uploaded_file($_FILES['csv']['tmp_name'], 'C:/xampp/htdocs/uploads/'.$new_file_name);
mysql_query("CREATE TABLE report_". $string ."(". $colNames .")") or die(mysql_error());
$sql = "LOAD DATA INFILE '/xampp/htdocs/uploads/report_". $string .".csv'
INTO TABLE report_". $string ."
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(". $insertColNames .")";
$query = mysql_query($sql) or die(mysql_error());
header('Location: download.php?dlname='.$string.'');
}
data.php (shortened most of this. In reality there are about 200 columns going in, twenty-thirty coming out)
<?php
$colNames = "Web_Site_Member_ID text,
Master_Member_ID text,
API_GUID text,
Constituent_ID text";
$insertColNames = "Web_Site_Member_ID,
Master_Member_ID,
API_GUID,
Constituent_ID";
$exportNames = "Web_Site_Member_ID, Date_Membership_Expires, Membership, Member_Type_Code";
?>
functions.php just includes the block of code for generating a random string/file name.
For CSV file reading please look at the fgetcsv() function. You should easily be able to extract a row of data and access each individual field in the resulting array for your column header definitions.

Import .CSV into MySQL DB

I have a script that I am using to import .CSV data into a MySQL DB. The first field of data (email address) still has quote marks around it when I pull into MySQL. The other fields, the quotes are stripped out.
My CSV lines looks like this:
"email4#email.com"," Karla","Smith"
"email5#email.com"," Carl","Nichols"
The email addresses still have quotes in MySQL. The first and last name are fine.
Any suggestions?
<?php
$conn = mysql_connect('host','username','password');
mysql_select_db('db-name');
mysql_query("TRUNCATE TABLE contacts") or die(mysql_error());
mysql_query("LOAD DATA LOCAL INFILE 'New Member Weekly Report for Marketing.csv'
INTO TABLE contacts
Fields terminated by ',' ENCLOSED BY '\"'
LINES terminated by '\r'(
contact_email
,contact_first
,contact_last)")
or die("Import Error: " . mysql_error());
?>
On a little bit of googling, I found this:
Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.
To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file.
You can then import it into a MySQL table by running:
load data local infile 'uniq.csv' into table tblUniq fields terminated by ','
enclosed by '"'
lines terminated by '\n'
(uniqName, uniqCity, uniqComments)
The fields here are the actual tblUniq table fields that the data needs to sit in. The enclosed by and lines terminated by are optional and can help if you have columns enclosed with double-quotes such as Excel exports, etc.
Source: http://www.tech-recipes.com/rx/2345/import_csv_file_directly_into_mysql/

Upload a csv and import it into the mysql database

I am writing the following script up import a csv file into a mysql database.
The user has to log in first and their security rights to upload are checked by another file, if this evaluates to true, the file can then be uploaded by the file up-loader which will only allow csv's to be uploaded and then the following part imports the file.
Am I using the correct code for this below ?, also if the csv layout is wrong is it possible to refuse the import ?, im just concerned that this could go badly wrong if the csv is formatted correctly. This feature has been requested as a requirement for this project so I am just trying to make it as idiot proof as possible for them.
<?php
$uploadedcsv = './uploads/'.$filename.'';
$sql = 'LOAD DATA LOCAL INFILE "'.$uploadedcsv.'" INTO TABLE '.$table.' FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY """" IGNORE 1 LINES' or die(mysql_error());
?>
Unless you are 100% rely on the user and it seems that you are not,
it will be good not to blindly import uploaded file, but first to check if it's correct.
To do it, you'll need to open and to read the file, e.g. with fgetcsv and to check the data consistency line-by-line.
You can find a lot of examples on the web.
Here are just some:
http://www.damnsemicolon.com/php/php-upload-csv-mysql
http://www.programmingfacts.com/import-csvexcel-data-mysql-database/
It can be done via MySQL, but by default LOAD DATA INFILE expects a different format than CSV. From the documentation:
If you specify no FIELDS or LINES clause, the defaults are the same as if you had written this:
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED BY '\n' STARTING BY ''
The documentation notes, for when dealing with CSV files:
LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
Which is an example of dealing with comma separated values enclosed by "" and line-separated by \r\n
To use this to import a file, make sure your statement matches the CSV format of your upload files and you can import via this manner.

Categories