note 111793 deleted from function.fgetcsv by aharvey
| From: | aharvey@php.net | Date: | Thu, 28 Mar 2013 17:52:43 +0000 |
| Subject: | note 111793 deleted from function.fgetcsv by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-194259@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
For importing CSV Data into MySQL tables
you need to change ['] to ['']
Example:
DROP TABLE IF EXISTS
mytable;
CREATE TABLE IF NOT EXISTS mytable (
value_1 varchar(255) NOT NULL,
value_2 varchar(255) NOT NULL,
value_3 varchar(255) NOT NULL,
value_4 varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO MYTABLE VALUES('val1','val2','val3','4
value''s');
<?php
$con = mysql_connect("localhost","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DB", $con);
// liest den Inhalt einer CSV Datei und speichert die Daten in einer MySQL Tabelle
$path = $_SERVER['DOCUMENT_ROOT'].(join(array_slice(split( "/"
,dirname($_SERVER['PHP_SELF'])),1,1),"/").'/');
$filename = "mydatafile.csv";
$table = "mydatatable";
$row = 1;
$entrynumber = 0;
$values = "";
if (($handle = fopen($path.$filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, filesize($filename), ",")) !== FALSE) {
$num = count($data);
$row++;
$values = "";
if($row<=2){
}else{
$entrynumber++;
for ($c=0; $c < ($num); $c++) {
$data[$c] = explode("'",$data[$c]);
$data[$c] = join("''",$data[$c]);
if($c< ($num-1)){
$values .= "'".$data[$c]."',";
}else{
$values .= "'".$data[$c]."'";
}
}
$select ="INSERT INTO ".$table." VALUES
(".utf8_decode($values).");";
$result = mysql_query($select);
mysql_error();
}
}
fclose($handle);
}
$select = "SELECT * FROM ".$table." ORDER BY
".$table.".id ASC";
$result = mysql_query($select);
$num_rows = mysql_num_rows($result);
echo('Entrys: '.$num_rows);
?>