Home  >  Article  >  php教程  >  利用PHP执行SQL文件,将SQL文件导入到数据库 - 郑宏鑫erke

利用PHP执行SQL文件,将SQL文件导入到数据库 - 郑宏鑫erke

WBOY
WBOYOriginal
2016-05-20 13:15:22934browse

如何利用php自动执行.sql文件,就是获取sql文件中的内容,然后将每一句sql语句一次执行。

代码example:

<span style="color: #008000;">//</span><span style="color: #008000;">读取文件内容</span>
$_sql = file_get_contents(<span style="color: #800000;">'</span><span style="color: #800000;">test.sql</span><span style="color: #800000;">'</span><span style="color: #000000;">);
 
$_arr </span>= explode(<span style="color: #800000;">'</span><span style="color: #800000;">;</span><span style="color: #800000;">'</span><span style="color: #000000;">, $_sql);
$_mysqli </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> mysqli(DB_HOST,DB_USER,DB_PASS);
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (mysqli_connect_errno()) {
    exit(</span><span style="color: #800000;">'</span><span style="color: #800000;">连接数据库出错</span><span style="color: #800000;">'</span><span style="color: #000000;">);
}
</span><span style="color: #008000;">//</span><span style="color: #008000;">执行sql语句</span>
<span style="color: #0000ff;">foreach</span> ($_arr <span style="color: #0000ff;">as</span><span style="color: #000000;"> $_value) {
    $_mysqli</span>->query($_value.<span style="color: #800000;">'</span><span style="color: #800000;">;</span><span style="color: #800000;">'</span><span style="color: #000000;">);
}
$_mysqli</span>-><span style="color: #000000;">close();
$_mysqli </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;

</span>

上面text.sql是你需要执行的sql文件,DB_HOST主机名,DB_USER用户名,DB_PASS密码!

这只是最基本的自动执行sql文件,你还可以自定义生成数据库的名称,方法就是将sql文件中下面的代码删去

<span style="color: #000000;">CREATE DATABASE IF NOT EXISTS 数据库名 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE 数据库名</span>

加上

$_mysqli->query(<span style="color: #800000;">"</span><span style="color: #800000;">CREATE DATABASE IF NOT EXISTS 数据库名 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;</span><span style="color: #800000;">"</span><span style="color: #000000;">);
$_mysqli</span>->query(<span style="color: #800000;">"</span><span style="color: #800000;">USE 数据库名</span><span style="color: #800000;">"</span>);

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn