Home > php教程 > php手册 > body text

PHP执行SQL文件并将SQL文件导入到数据库

WBOY
Release: 2016-06-06 19:44:26
Original
1081 people have browsed it

今天给大家介绍一下,如何利用php自动执行.sql文件。其实很简单,就是获取sql文件中的内容,然后将每一句sql语句一次执行就行啦。需要的朋友可以参考下

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

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

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

CREATE DATABASE IF NOT EXISTS 数据库名 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

USE 数据库名

然后在text.php中执行所有的sql语句前添加代码

$_mysqli->query("CREATE DATABASE IF NOT EXISTS 数据库名 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"); $_mysqli->query("USE 数据库名");

以上就是本文的全部内容,,希望对大家有所帮助。

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!