天天看點

快速導入的大檔案(sql)的php程式

<?

//用來快速Mysql的大資料備份

//使用前請首先按照代碼注釋修改要導入的SQL檔案名、資料庫主機名、資料庫使用者名、密碼、資料庫名

//同時将資料庫檔案和本文本一起ftp導網站目錄,然後以web方式通路此檔案即可

//落伍(www.im286.com)負翁版權所有,可随意使用,但保留版權資訊

        $file_name="sql.sql";  //要導入的SQL檔案名

        $dbhost="localhost"; //資料庫主機名

        $dbuser="user"; //資料庫使用者名

        $dbpass="pass";          //資料庫密碼

        $dbname="dbname";      //資料庫名

        set_time_limit(0); //設定逾時時間為0,表示一直執行。當php在safe mode模式下無效,此時可能會導緻導入逾時,此時需要分段導入

        $fp = @fopen($file_name, "r") or die("不能打開SQL檔案 $file_name");//打開檔案

        mysql_connect($dbhost, $dbuser, $dbpass) or die("不能連接配接資料庫 $dbhost");//連接配接資料庫

        mysql_select_db($dbname) or die ("不能打開資料庫 $dbname");//打開資料庫

  mysql_query('set names utf8');

        echo "正在執行導入操作";

        while($SQL=GetNextSQL()){

                if (!mysql_query($SQL)){

                        echo "執行出錯:".mysql_error()."

";

                        echo "SQL語句為:

".$SQL."

";

                };

        }

        echo "導入完成";

        fclose($fp) or die("Can’t close file $file_name");//關閉檔案

        mysql_close();

        //從檔案中逐條取SQL

        function GetNextSQL() {

                global $fp;

                $sql="";

                while ($line = @fgets($fp, 40960)) {

                        $line = trim($line);

                        //以下三句在高版本php中不需要,在部分低版本中也許需要修改

                        $line = str_replace("","//",$line);

                        $line = str_replace("/’","’",$line);

                        $line = str_replace("//r//n",chr(13).chr(10),$line);

//                        $line = stripcslashes($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;

        }

?>