Web Hosting Forum | Lunarpages


*
Welcome, Guest. Please login or register.
Did you miss your activation email?



Login with username, password and session length
February 09, 2012, 05:09:34 PM

Pages: [1]   Go Down
  Print  
Author Topic: Importing CSV files into PHPMyAdmin  (Read 2197 times)
simontheak
Intergalactic Cowboy
*****
Offline Offline

Posts: 71


WWW
« on: May 16, 2010, 05:06:44 AM »

Hi there,

Can someone advise the best way to import a CSV file into a database using PHPMyAdmin?

I've created a database, set up some tables and would like to import my CSV data into one of the tables.

Thanks a lot,
Logged

MrPhil
Berserker Poster
*****
Offline Offline

Posts: 5083



« Reply #1 on: May 16, 2010, 07:48:08 AM »

I just tried phpMyAdmin > Import and the only option it offered me was "SQL" formatted file. If you can't find a way to directly import a CSV file, you have two options:

1) If it's a "one off" job, manually (or with a script) turn your CSV file into a .sql file with the data formatted into an INSERT statement:
Code:
INSERT INTO tablename (field1, field2, field3,...) VALUES
('data1-1', 'data1-2', 'data1-3',...)
,('data2-1', 'data2-2', 'data2-3',...)
etc. That can be IMPORTed into phpMyAdmin. Do up to 100 records at a time.

2) If it's something that's going to be done repeatedly, write a PHP script to read in the CSV file and build an SQL query that looks like the above:
Code:
mysql_connect(....);
mysql_selectdb(....);
$count = 0;
while(true) {
  if ($count==0) $query = 'INSERT INTO tablename (field1, field2, field3,...) VALUES';
  if ($count>0) $query .= ',';
  $count++;
  ... read in one row
  if (eof on input) {
    if ($count>1) mysql_query($query);  // might do error checking here
    break;
  }
  $query .= "('" . $data1 . "','" . $data2..... "')";
  if ($count==100) {
    mysql_query($query);  // might do error checking here
    $count = 0;
  }
}
Or something close to that. Obviously, at a minimum you want to give an obscure name to the script so that hackers can't stumble across it and mess up your database.
Logged

scanman20
Über Jedi
*****
Offline Offline

Posts: 1520



WWW
« Reply #2 on: May 16, 2010, 08:32:19 AM »

I just checked my phpmyadmin because this sounded familiar and I have three options for importing: CSV, CSV using LOAD DATA, and SQL. If you go to the import tab before selecting a table, you'll only see SQL as an option, but if you go to a table first and then click the import tab, you should see what I described.
Logged

Even a broken clock is right twice a day.
NotOneBit.com
MCSE - MCSA - MCP
simontheak
Intergalactic Cowboy
*****
Offline Offline

Posts: 71


WWW
« Reply #3 on: May 16, 2010, 10:00:58 AM »

Thanks Scanman - you're a star Smile
Logged

Pages: [1]   Go Up
  Print  
 
Jump to: