欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何利用PHP执行.SQL文件

程序员文章站 2023-01-02 17:47:41
demo.php:复制代码 代码如下:
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
                            )
                        )

                    );

            foreach($segment as & $statement)
            {
                $tokens = split(" ",$statement[0]);

                $tablename = array();
                $this->findtablename($sqlflagtree,$tokens,0,$tablename);

                if(empty($tablename['leftwall']))
                {
                    $newtablename = $prefix.$tablename['name'];
                }
                else{
                    $newtablename = $tablename['leftwall'].$prefix.substr($tablename['name'],1);
                }

                $statement[0] = str_replace($tablename['name'],$newtablename,$statement[0]);
            }

        }      
        //组合sql语句
        foreach($segment as & $statement)
        {
            $newstmt = '';
            foreach($statement as $sentence)
            {
                $newstmt = $newstmt.trim($sentence)."/n";
            }

            $statement = $newstmt;
        }

        //用于测试------------------------      
        //var_dump($segment);
        //writearraytofile('data.txt',$segment);
        //-------------------------------

        self::savebyquery($segment);

        return true;
    }

    private function savebyquery($sqlarray)
    {
        $conn = mysql_connect($this->dbhost,$this->dbuser,$this->dbpassword);

        mysql_select_db($this->dbschema);

        foreach($sqlarray as $sql)
        {
            mysql_query($sql);
        }      
        mysql_close($conn);
    }

    private function findtablename($sqlflagtree,$tokens,$tokenskey=0,& $tablename = array())
    {
        $regxleftwall = "^[/`/'/"]{1}";

        if(count($tokens)<=$tokenskey)
            return false;      

        if('' == trim($tokens[$tokenskey]))
        {
            return self::findtablename($sqlflagtree,$tokens,$tokenskey+1,$tablename);
        }
        else
        {
            foreach($sqlflagtree as $flag => $v)
            {  
                if(eregi($flag,$tokens[$tokenskey]))
                {
                    if(0==$v)
                    {
                        $tablename['name'] = $tokens[$tokenskey];

                        if(eregi($regxleftwall,$tablename['name']))
                        {
                            $tablename['leftwall'] = $tablename['name']{0};
                        }

                        return true;
                    }
                    else{
                        return self::findtablename($v,$tokens,$tokenskey+1,& $tablename);
                    }
                }
            }
        }

        return false;
    }
}
function writearraytofile($filename,$dataarray,$delimiter="/r/n")
{
    $handle=fopen($filename, "wb");

    $text = '';

    foreach($dataarray as $data)
    {
        $text = $text.$data.$delimiter;
    }
    fwrite($handle,$text);
}
//测试
$dbm = new dbmanager('localhost','w01f','123456','test');
$dbm->createfromfile('data.sql',null,'fff_');
?>

data.sql:
-- phpmyadmin sql dump
-- version 2.11.3
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2008 年 08 月 20 日 12:09
-- 服务器版本: 5.0.51
-- php 版本: 5.2.5
set sql_mode="no_auto_value_on_zero";
--
-- 数据库: `newysh`
--
-- --------------------------------------------------------
--
-- 表的结构 `allowed`
--
create table `allowed` (
`bhash` blob not null,
`bname` varchar(255) character set utf8 not null,
primary key (`bhash`(20))
) engine=myisam default charset=gb2312 row_format=dynamic;
--
-- 导出表中的数据 `allowed`
--
-- --------------------------------------------------------
--
-- 表的结构 `allowed_ex`
--
create table `allowed_ex` (
`bhash` blob not null,
`badded` datetime not null,
`bsize` bigint(20) unsigned not null,
`bfiles` int(10) unsigned not null,
primary key (`bhash`(20))
) engine=myisam default charset=gb2312 row_format=dynamic;
--
-- 导出表中的数据 `allowed_ex`
--
-- --------------------------------------------------------
--
-- 表的结构 `category`
--
create table `category` (
`cid` int(10) unsigned not null auto_increment comment '种子分类id',
`name` varchar(255) not null comment '分类名称,支持html格式',
`sequence` int(10) unsigned not null comment '显示排序,需要小的排在前面',
primary key (`cid`)
) engine=myisam default charset=utf8 auto_increment=26 ;
--
-- 导出表中的数据 `category`
--
insert into `category` (`cid`, `name`, `sequence`) values
(25, '音乐', 23),
(24, '学习资料', 24),
(23, '电影', 25);
-----------------------------------------------------------
注:对于phpmyadmin 生成的sql文件均适用