Here is the sample code:
<?php
function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
if (($handle = fopen($source_file, "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, ",");
foreach ($columns as &$column) {
$column = str_replace(".","",$column);
}
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while(count($data) < count($columns)) {
array_push($data, NULL);
}
$c = count($data);
for($i = 0; $i < $c; $i++) {
$data[$i] = "'{$data[$i]}'";
}
$sql[] = '(' . implode(',',$data) . ')';
}
$query = "INSERT INTO $target_table (".implode(",",$columns).")VALUES " . implode(',',$sql) . "\n";
echo $query;
fclose($handle);
}
}
$file = 'test.csv';
$table = 'test';
csv_file_to_mysql_table($file,$table);
?>
So now it will echo : INSERT INTO Mytable (FirstName,LastName) VALUES ('A','B').I put echo instead of mysql_query($query) because I just want to see how is the query.
I tried to add ` for each of my column name , but get error.
Can I get some hints how to add it?
You could use array_map with a comma join to do this:
You could also use this to make doing the values a little easier too:
I use these a lot when I have an array structure like:
array(‘FirstName’ => ‘A’, ‘LastName => ‘B’);
Then I can just do this (using PDO and prepared statements):
Which will ensure my data is put in safely, matching the named paramaters to the $posted array.
Note: This does require 5.3, but you can just take out the inline functions, and make them real functions for earlier php versions.
like: