|
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]
|