PDA

View Full Version : CSV to MySQL dump file



oates151
November 17th, 2007, 12:27
Hello everyone,

I need to import data (names) into a database on mysql. The document has three columns; first name, last name, gender. I'd like to know if it is possible to convert this CSV document into a .SQL with the following format for each name:

INSERT INTO `students` (`sid`, `s_firstname`, `s_lastname`, `gender`) VALUES (1, 'John, 'Smith, 'M');

Thanks everyone,

Pat

Decker
November 17th, 2007, 12:37
http://www.google.co.uk/search?hl=en&q=convert+csv+to+mysql&meta=

First result, funny ain't it ??

Doesn't say a lot for Galaxy Webs Development Services & GalaxyWebs.com

Pat it's easy, just look.

oates151
November 17th, 2007, 14:23
I tried uploading the CSV files before, but I got an error in phpMyadmin on line 1.

krakjoe
November 17th, 2007, 14:36
paste the first few lines of the csv file ....

oates151
November 17th, 2007, 14:42
Warren,Abrahamsen,M
Louis,Adamo,M
Steven,Antonio,M
Anthony,Ardizzone,M
Andrew,August,M
Joseph,Baker,M
Charles,Bayham III,M

thats the first few lines from the doc when I opened it in notepad

krakjoe
November 17th, 2007, 15:01
<?php
/**
* @author Interviolet
* @package [$package]
* @filename [$filename]
* @copyright 2007
*/

function csv2sql( $file )
{
if( ( $read = fopen( $file, 'r' ) ) )
{
if( ( $write = fopen( "$file.sql", "w" ) ) )
{
while( !feof( $read ) )
{
if( ( $line = @split( ',', fgets( $read ) ) ) and count( $line ) == 3 );
{
$line = array_map( 'trim', $line );

if( !fwrite( $write, sprintf( "INSERT INTO `students` VALUES('', '&#37;s', '%s', '%s');\r\n", $line[0], $line[1], $line[2] ) ) )
{
die( "cannot write to $file.sql" );
}
$line++;
}
}
printf( "Wrote %d bytes of sql queries to %s.sql", ftell( $write ), $file );
fclose( $read );
fclose( $write );
}
else printf( "Cannot open %s.sql for writing\r\n", $file );
}
else printf( "Cannot open %s for reading\r\n", $file );
}
csv2sql( "file.txt" );
?>


will produce and save



INSERT INTO `students` VALUES('', 'Warren', 'Abrahamsen', 'M');
INSERT INTO `students` VALUES('', 'Louis', 'Adamo', 'M');
INSERT INTO `students` VALUES('', 'Steven', 'Antonio', 'M');
INSERT INTO `students` VALUES('', 'Anthony', 'Ardizzone', 'M');
INSERT INTO `students` VALUES('', 'Andrew', 'August', 'M');
INSERT INTO `students` VALUES('', 'Joseph', 'Baker', 'M');
INSERT INTO `students` VALUES('', 'Charles', 'Bayham III', 'M');


to file.txt.sql, when file.txt is



Warren,Abrahamsen,M
Louis,Adamo,M
Steven,Antonio,M
Anthony,Ardizzone,M
Andrew,August,M
Joseph,Baker,M
Charles,Bayham III,M