Home  >  Article  >  Backend Development  >  How to use php to automatically execute .sql files

How to use php to automatically execute .sql files

墨辰丷
墨辰丷Original
2018-06-07 09:50:522558browse

This article mainly introduces how to use php to automatically execute .sql files. Interested friends can refer to it. I hope it will be helpful to everyone.

//Read file contents
$_sql = file_get_contents('test.sql');
$_arr = explode(';', $_sql);
$_mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS);
if (mysqli_connect_errno()) {
exit('Error connecting to database');
}
//Execute sql statement
foreach ($_arr as $_value) {
$_mysqli->query($_value.';');
}
$_mysqli->close();
$_mysqli = null;

The above text.sql is the sql file you need to execute, DB_HOST host name, DB_USER user name, DB_PASS password!

This is just the most basic automatic execution sql file, you can also customize the generated database Name, the method is to delete the following code in the sql file

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

USE database name

Then add the code before executing all sql statements in text.php

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

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Detailed explanation of PHP (iterative recursion) to achieve infinite classification

php implementation supports Chinese File download

Detailed explanation and cases of connecting Mongodb to remote database under PHP

The above is the detailed content of How to use php to automatically execute .sql files. For more information, please follow other related articles on the PHP Chinese website!

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