Home  >  Article  >  Backend Development  >  PHP执行SQL文件并将SQL文件导入到数据库_php实例

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

WBOY
WBOYOriginal
2016-06-07 17:11:35730browse

//读取文件内容
$_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 数据库名");

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

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