萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> 如何利用PHP執行.SQL文件

如何利用PHP執行.SQL文件

本篇文章是對使用PHP執行.SQL文件的實現代碼進行了詳細的分析介紹,需要的朋友參考下  

demo.php:

復制代碼 代碼如下:
<?php
/**
* 讀取 sql 文件並寫入數據庫
* @version 1.01 demo.php
*/
class DBManager
{
    var $dbHost = '';
    var $dbUser = '';
    var $dbPassword = '';
    var $dbSchema = '';

    function __construct($host,$user,$password,$schema)
    {
        $this->dbHost = $host;
        $this->dbUser = $user;
        $this->dbPassword = $password;
        $this->dbSchema = $schema;
    }

    function createFromFile($sqlPath,$delimiter = '(;/n)|((;/r/n))|(;/r)',$prefix = '',$commenter = array('#','--'))
    {
        //判斷文件是否存在
        if(!file_exists($sqlPath))
            return false;

        $handle = fopen($sqlPath,'rb');  

        $sqlStr = fread($handle,filesize($sqlPath));

        //通過sql語法的語句分割符進行分割
        $segment = explode(";",trim($sqlStr));

        //var_dump($segment);

        //去掉注釋和多余的空行
        foreach($segment as & $statement)
        {
            $sentence = explode("/n",$statement);

            $newStatement = array();

            foreach($sentence as $subSentence)
            {
                if('' != trim($subSentence))
                {
                    //判斷是會否是注釋
                    $isComment = false;
                    foreach($commenter as $comer)
                    {
                        if(eregi("^(".$comer.")",trim($subSentence)))
                        {
                            $isComment = true;
                            break;
                        }
                    }
                    //如果不是注釋,則認為是sql語句
                    if(!$isComment)
                        $newStatement[] = $subSentence;                  
                }
            }

            $statement = $newStatement;
        }
        //對表名加前綴
        if('' != $prefix)
        {

      
            //只有表名在第一行出現時才有效 例如 CREATE TABLE talbeName

            $regxTable = "^[/`/'/"]{0,1}[/_a-zA-Z]+[/_a-zA-Z0-9]*[/`/'/"]{0,1}$";//處理表名的正則表達式
            $regxLeftWall = "^[/`/'/"]{1}";

            $sqlFlagTree = array(
                    "CREATE" => array(
                            "TABLE" => array(
                                    "$regxTable" => 0
                                )
                        ),
                    "INSERT" => array(
                            "INTO" => array(
                                "$regxTable" => 0
                            )
                        )

                    );

        
copyright © 萬盛學電腦網 all rights reserved