· 10 years ago · Jul 30, 2016, 10:54 PM
1<?php
2
3$host = 'localhost';
4$user = 'root';
5$pass = '';
6$database = 'database';
7
8$db = mysql_connect($host, $user, $pass);
9mysql_query("use $database", $db);
10
11/********************************************************************************/
12// Parameters: filename.csv table_name
13
14$argv = $_SERVER[argv];
15
16if($argv[1]) { $file = $argv[1]; }
17else {
18 echo "Please provide a file name\n"; exit;
19}
20if($argv[2]) { $table = $argv[2]; }
21else {
22 $table = pathinfo($file);
23 $table = $table['filename'];
24}
25
26/********************************************************************************/
27// Get the first row to create the column headings
28
29$fp = fopen($file, 'r');
30$frow = fgetcsv($fp);
31
32foreach($frow as $column) {
33 if($columns) $columns .= ', ';
34 $columns .= "`$column` varchar(250)";
35}
36
37$create = "create table if not exists $table ($columns);";
38mysql_query($create, $db);
39
40/********************************************************************************/
41// Import the data into the newly created table.
42
43$file = $_SERVER['PWD'].'/'.$file;
44$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
45mysql_query($q, $db);
46
47?>