I’m now using this code to import csv data into my database.(Thanks to Francis Avila)
if (($handle = fopen($source_file, "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, ",");
$esc_columns = array();
foreach ($columns as &$column) {
$column1 = str_replace(".","",$column);
$column = preg_replace("/\s*,\s*/",",",$column1);
$esc_columns[] = escapeSqlName($column);
}
$esc_columns[] = escapeSqlName('custgroup');
$esc_columns[] = escapeSqlName('user_id');
$esc_columns[] = escapeSqlName('mylabel');
$x = preg_replace("/\s*,\s*/", ",", implode(',',$esc_columns));
$xx = str_replace(' ', '', $x);
$sqlsmttempl = 'INSERT DELAYED INTO %s (%s) VALUES (%s)';
$sqlsmt = sprintf($sqlsmttempl,
escapeSqlName($target_table),
$xx,
implode(',',array_fill(0, count($esc_columns), '?'))
);
$db = new PDO("mysql:host=localhost;dbname=Data;","root","");
$insert = $db->prepare($sqlsmt);
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while(count($data) < count($columns)) {
$data[] = NULL;
}
$data[] = $_POST['custgroup'];
$data[] = $_POST['user_id'];
$data[] = $_POST['mylabel'];
$insert->execute($data);
}
I faced some problem in header blank space before , so I added
$x = preg_replace("/\s*,\s*/", ",", implode(',',$esc_columns));
$xx = str_replace(' ', '', $x);
so now blank space will be ignored.
But how about blank space in data?(just in front and end of comma) . I tried trim($data) , but I know it is wrong.
And I have no clue how to handle the upload when the header contain other extra commas , such as :
Name,Address,Phone,,,,,(wrong) instead of just Name,Address,Phone(correct)
Any advice?Thanks in advance.
The problem can be solved by using rtrim ( string $str [, string $charlist ] ):
For triming text in php you can use : ltrim (left trim), trim (trim on both sides), rtrim (right trim). All accept parameters ( string $str [, string $charlist ] ) $str – input string $charlist – string to be trimed
You cand add many commands as you want:
Note: