sql - Import CSV File into a SQLite Database via PHP -
i want import table csv file sqlite db via php script can manually run update data.
heres list of want achieve:
- rename old table (which called "produkte") product-currentdate (or drop table)
- then import files csv file (
;
separated , iso 8859-1 charset / first row of csv-file contains table header) - save date in table "product"
i've found script reason not work:
<?php $dir = 'sqlite:test.sqlite'; $dbh = new pdo($dir) or die("cannot open database"); $query = <<<eof load data local infile 'produkte.csv' table produkte fields terminated ';' optionally enclosed '"' lines terminated '\n' ignore 1 lines (id, hauptmenue, produktgruppe, beschreibung, text, bild, shop, info) eof; $dbh->query($query); ?>
i hope knows how solve problem...
best regards dave
federico cingolani has posted php script @ github meets needs
<?php function import_csv_to_sqlite(&$pdo, $csv_path, $options = array()) { extract($options); if (($csv_handle = fopen($csv_path, "r")) === false) throw new exception('cannot open csv file'); if(!$delimiter) $delimiter = ','; if(!$table) $table = preg_replace("/[^a-z0-9]/i", '', basename($csv_path)); if(!$fields){ $fields = array_map(function ($field){ return strtolower(preg_replace("/[^a-z0-9]/i", '', $field)); }, fgetcsv($csv_handle, 0, $delimiter)); } $create_fields_str = join(', ', array_map(function ($field){ return "$field text null"; }, $fields)); $pdo->begintransaction(); $create_table_sql = "create table if not exists $table ($create_fields_str)"; $pdo->exec($create_table_sql); $insert_fields_str = join(', ', $fields); $insert_values_str = join(', ', array_fill(0, count($fields), '?')); $insert_sql = "insert $table ($insert_fields_str) values ($insert_values_str)"; $insert_sth = $pdo->prepare($insert_sql); $inserted_rows = 0; while (($data = fgetcsv($csv_handle, 0, $delimiter)) !== false) { $insert_sth->execute($data); $inserted_rows++; } $pdo->commit(); fclose($csv_handle); return array( 'table' => $table, 'fields' => $fields, 'insert' => $insert_sth, 'inserted_rows' => $inserted_rows ); }
Comments
Post a Comment