Hongmu Notes
Home Language Notes php import sql file into database
Language Notes PHP PHP collection PHP and mysql

php import sql file into database

php import sql file into database

PHP imports sql files into the database, often used to install source code

Encapsulates a class, taken from the Internet


<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/13
 * Time: 10:25
 */
class ImportData{
    //数据库信息
    private $dbhost;
    private $dbuser;
    private $dbpw;
    private $dbport;
    private $dbname;
    private $dbcharset;
    private $link;
    private $tablepre;
    public function __construct($data)
    {
         $this->dbhost=isset($data['dbhost'])?$data['dbhost']:'';
         $this->dbuser=isset($data['dbuser'])?$data['dbuser']:'';
         $this->dbpw=isset($data['dbpw'])?$data['dbpw']:'';
         $this->dbport=isset($data['dbport'])?$data['dbport']:'3306';
         $this->dbname=isset($data['dbname'])?$data['dbname']:'';
         $this->dbcharset=isset($data['dbcharset'])?$data['dbcharset']:'utf8';
         $this->tablepre=isset($data['tablepre'])?$data['tablepre']:'';
         $link_info=$this->link_data();
         if(!$link_info['status']){
             return $link_info;
         }
    }

    //链接设置数据库
    protected function link_data(){
        $link=mysqli_connect($this->dbhost,$this->dbuser,$this->dbpw,null,$this->dbport);
        if(!$link)
            return array('status'=>false,'info'=>'数据库连接失败');
        else
            $this->link=$link;
        //mysql 版本
        //获得mysql版本
        $version = mysqli_get_server_info($this->link);
        //设置字符集
        if($version > '4.1' && $this->dbcharset) {
            mysqli_query($link, "SET NAMES {$this->dbcharset}");
        }
        //选择数据库
        mysqli_select_db($this->link,$this->dbname);
    }

    //导数据

    /**
     * @param $dbfile  要导入的sql数据文件
     * @param string $dbfile_table_pre  导入的sql文件的表前缀
     * @return array
     */
    public function import_data($dbfile,$dbfile_table_pre='zq_'){
        if(!file_exists($dbfile)){
           return array('status'=>false,'info'=>'数据库文件不存在');
        }
        $sql = file_get_contents($dbfile);
        $status=$this->_sql_execute($this->link, $sql,$dbfile_table_pre);
        if($status){
//            echo '导入数据库成功';
            return array('status'=>true,'info'=>'导入数据库成功');
        }else{
            return array('status'=>true,'info'=>'导入数据库失败');
//            echo '导入数据库失败';
        }

    }

    /**
     * @param $link  数据库链接
     * @param $sql   要导入的sql语句
     * @param $dbfile_table_pre 导入的sql文件的表前缀
     * @return bool
     */
   protected function _sql_execute($link,$sql,$dbfile_table_pre) {
        $sqls =$this-> _sql_split($link,$sql,$dbfile_table_pre);
        if(is_array($sqls))
        {
            foreach($sqls as $sql)
            {
                if(trim($sql) != '')
                {
                    mysqli_query($link,$sql);
                }
            }
        }
        else
        {
            mysqli_query($link,$sqls);
        }
        return true;
    }

    /**
     * @param $link  表链接对象
     * @param $sql   导入的sql
     * @param $dbfile_table_pre  sql文件中的sql表前缀
     * @return array
     */
    protected function _sql_split($link,$sql,$dbfile_table_pre) {
        if(mysqli_get_server_info($link) > '4.1' && $this->dbcharset)
        {
            $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=".$this->dbcharset,$sql);
        }
        //如果有表前缀就替换现有的前缀
        if($this->tablepre){
            $sql=str_replace($dbfile_table_pre, $this->tablepre, $sql);
        }
        $sql = str_replace("\r", "\n", $sql);
        $ret = array();
        $num = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach($queriesarray as $query)
        {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            $queries = array_filter($queries);
            foreach($queries as $query)
            {
                $str1 = substr($query, 0, 1);
                if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
            }
            $num++;
        }
        return $ret;
    }
}
/**
 * 初始化数据库信息
 */
$data=array(
     'dbhost'=>'127.0.0.1'
    ,'dbuser'=>'root'
    ,'dbpw'=>'root'
    ,'dbname'=>'phptest'
);
$obj=new ImportData($data);
$obj->import_data('./zq.sql');
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232
PHP special character escaping and restoration

PHP special character escaping and restoration Language Notes PHP PHP collection PHP and mysql

Escape character is a special character constant. Escape characters are backslashed " & quot; At the beginning, followed by one or more characters. The escaped character has a specific meaning, which is different from the original meaning of the character, so it is called "escaped" character. The use of escape characters 1: turn ordinary characters into special purposes, such as back key and enter key. 2. Used to convert a character with special meaning back to its original meaning. 3. Before data is written into the database, escape characters (function …
👁 180
mysqli in PHP

mysqli in PHP Language Notes PHP PHP collection PHP and mysql

The `mysqli_num_rows()` function is exclusively used with `SELECT` query methods, whereas the `mysqli_affected_rows()` function returns the number of rows affected by the previous SQL statement across the entire database; this function is primarily used with `INSERT`, `UPDATE`, and `DELETE` operations.
👁 145

Recommended reading

(Adaptive Mobile Version) Bilingual (Chinese/English) Stroller Safety Seat Website Template – 0957

(Adaptive Mobile Version) Bilingual (Chinese/English) Stroller Safety Seat Website Template – 0957 Practical Collection pbootcms Template

A bilingual (Chinese/English) stroller safety seat website template for PbootCMS, compatible with both PC and WAP devices. The professional and safety-focused design is ideal for maternal and infant product companies seeking to showcase their products in the international market. The multilingual support facilitates effective brand promotion across global markets. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles: Pbo...
👁 57
Linux command to query a large file directory on a server

Linux command to query a large file directory on a server Summary of pitfalls

You can use the `du` command to check the size of each folder in a Linux file system and identify the largest folders among them. Enter the following command in your terminal to find all folders larger than 1 GB and sort them in descending order by size: `du-h / | grep '[0-9\.]\+G' | sort-rh`. Here, `/` is the root directory you want to search, and `-h` specifies...
👁 282
Fruit and Vegetable Farm Website Template 1210

Fruit and Vegetable Farm Website Template 1210 Practical Collection Yiyou template

An EyouCMS website template designed specifically for fruit and vegetable farms. Its fresh and natural design effectively showcases the farming environment, produce offerings, harvesting experiences, and brand stories. This template helps agricultural businesses showcase their products online and expand their sales channels. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Eyou...
👁 67
(Adaptive mobile version) SEO-optimized corporate website template – 0958

(Adaptive mobile version) SEO-optimized corporate website template – 0958 Practical Collection pbootcms Template

A PbootCMS website template designed for SEO-optimized websites, compatible with both PC and WAP devices. Its modern, tech-driven design makes it ideal for SEO service providers and web development companies to showcase their project examples and optimization results. It helps internet marketing agencies attract corporate clients online. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 39
Responsive Pu-erh Tea Product Display Template 1211

Responsive Pu-erh Tea Product Display Template 1211 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for showcasing tea and Pu-erh tea products. Its classical and elegant design allows you to effectively present Pu-erh tea products, brand stories, tea ceremony culture, and sales information. It helps Pu-erh tea brands showcase their products online and attract tea enthusiasts. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 31