Home > Backend Development > PHP Tutorial > PHP执行SQL文件并将SQL文件导入到数据库_PHP

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

WBOY
Release: 2016-05-28 15:04:58
Original
823 people have browsed it


//读取文件内容
$_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;
Copy after login

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

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

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

USE 数据库名

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

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

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

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template