php代码将数据导入多个表

时间:2011-01-22 09:50:51

标签: php

这适用于1个表,但我如何为多个表执行此操作?

$ databasehost =“localhost”; $ databasename =“test”; $ databasetable =“sample”; $ databaseusername =“test”; $ databasepassword =“”; $ fieldseparator =“,”; $ lineseparator =“\ n”; $ csvfile =“filename.csv”;

$ addauto = 0;

if(!file_exists($ csvfile)){  echo“找不到文件。请确保指定了正确的路径。\ n”;  出口; }

$ file = fopen($ csvfile,“r”);

if(!$ file){  echo“打开数据文件时出错。\ n”;  出口; }

$ size = filesize($ csvfile);

if(!$ size){  echo“文件为空。\ n”;  出口; }

$ csvcontent = fread($ file,$ size);

FCLOSE($文件);

$ con = @mysql_connect($ databasehost,$ databaseusername,$ databasepassword)或die(mysql_error()); @mysql_select_db($ databasename)或die(mysql_error());

$ lines = 0; $ queries =“”; $ linearray = array();

foreach(拆分($ lineseparator,$ csvcontent)为$ line){

$线++;

$ line = trim($ line,“\ t”);

$ line = str_replace(“\ r”,“”,$ line);

$ line = str_replace(“'”,“\'”,$ line);

$ linearray = explode($ fieldseparator,$ line);

$ linemysql = implode(“','”,$ linearray);

如果($ addauto)   $ query =“insert into $ databasetable values('','$ linemysql');”;  其他   $ query =“insert into $ databasetable values('$ linemysql');”;

$ queries。= $ query。 “\ n” 个;

@mysql_query($查询); }

@mysql_close($ CON);

>

1 个答案:

答案 0 :(得分:0)

if($addauto) $query = "insert into $databasetable values('','$linemysql');"; else $query = "insert into $databasetable values('$linemysql');";

$queries .= $query . "\n";

- >

$tables = array('sample','sample2');
foreach( $tables as $table )
{
   if($addauto) 
       $query = "insert into $table values('','$linemysql');";
   else
       $query = "insert into $table values('$linemysql');";
   $queries .= $query . "\n";
}