search
Homephp教程php手册PHP执行SQL文件并将SQL文件导入到数据库,

PHP执行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 数据库名");

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool