You are here: Re: Importing csv file into mysql « All PHP « IT news, forums, messages
Re: Importing csv file into mysql

Posted by Rik on 03/02/07 11:19

On Fri, 02 Mar 2007 11:42:49 +0100, kenoli <kenoli.p@gmail.com> wrote:

> I have tried two php scripts in an attempt to load data exported from
> an Exel file into a mysql database. One I found in the archive for
> this group and another elsehwere. Here are the scripts:

fgetcsv() is your friend.

<?php
// set parameters
$file =3D '/my/csv/file';
$tablename =3D 'table';
$fields =3D array(
'field1',
'field2',
'field3');
//Go:
$handle =3D fopen($file,'r') or die('File not found.');
$cols =3D count($fields);
$row =3D '('.str_repeat("'%s'",$cols).')';
$query =3D "INSERT INTO `{$tablename}` (`".implode('`,`',$fields)."`) VA=
LUES =

";
$line =3D 1;
$inserts =3D array();
while($array =3D fgetcsv($handle)){ //change parameters according to for=
mat =

of you csv
if(count($array) !=3D $cols) die ('Invalid data on line '.$line);
array_walk($array,'mysql_real_escape_string');
$insert[] =3D vsprintf($row,$array);
$line++;
}
if(!empty($inserts)){
$query .=3D implode(',',$inserts);
//connect to db
mysql_query($query) or die('Problem with query:'.$query.' MySQL =

said:'.mysql_error());
} else {
echo 'Nothing to insert';
}
?>

Allthough it's not advisable to insert integers this way in a database..=
...
-- =

Rik Wasmus

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация