php导入大量数据到mysql(示例)

发布时间:2020-06-01编辑:脚本学堂
分享一例实现导入大量数据到mysql数据库中的php代码,学习下php导入mysql数据的方法,有需要的朋友参考下。

本节内容:
php导入数据到mysql/ target=_blank class=infotextkey>mysql数据库

例子:
 

复制代码 代码示例:

<?php
//快速Mysql的大数据备份
//使用前请首先按照代码注释修改要导入的SQL文件名、数据库主机名、数据库用户名、密码、数据库名。
//同时将数据库文件和文本一起ftp导网站目录,然后以WEB方式访问此文件即
//edit: www.jb200.com
$file_name="bn_site.sql";//要导入的SQL文件名
$dbhost="localhost";//数据库主机名
$dbuser="root";//数据库用户名
$dbpass="";//数据库密码
$dbname="bn_site"; //数据库名
set_time_limit(0);//设置超时间为0,表示一直执行。当php在safe mode模式下无效此时就会导入超时,此时需要分段导入
$fp=@fopen($file_name,"r") or die ("不能打开SQL文件");//打开文件
mysql_connect($dbhost,$dbuser,$dbpass) or die("不能连接数据库"); //连接数据库
mysql_select_db($dbname) or die("不能打开数据库");//打开数据库
echo "正在执行导入操作";
while($SQL=GETNEXTSQL()){
if(!mysql_query($sql)){
echo "<font color=red>执行出错:".mysql_error()."</font><br>";
echo "sql语句为:<br>".$SQL."<br>";
};

}
echo "导入完成</span>";

fclose($fp) or die ("can"t close file $file"); //关闭文件
mysql_close();
//从文件中逐条取SQL
function GETNETSQL(){
global $fp;
$sql="";
while( $line=@fgets($fp,40960)){
$line=trim($line);
//一下三句在高版本php中不需要,在部分低版本中也许需要修改
$line = str_replace(“\”,””,$line);
$line = str_replace(“’”,”‘”,$line);
$line = str_replace(“rn”,chr(13).chr(10),$line);
if (strlen($line)>1){
if ($line[0]=="-"&& $line[1]=="-"){
  continue;
}
}

$sql.=$line.chr(13).chr(10);
if (strlen($line)>0){
    if ($line[strlen($line)-1]==";"){
break;
}
}
}
return $sql;
}
?>