如何在一个tables.sql文件中编写多个查询并使用php上传?

ndasle7k  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(365)

我只想使用 tables.sql 文件通过php。

php创建\u db.php

<?php
require 'config.php';

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
/* check connection */
if($mysqli->connect_errno){
  echo "MySQL connection failed.<br>";
  exit();
}else{
  echo "MySQL successfully connected.<br>";
}

// DB create
if($mysqli->query('CREATE DATABASE IF NOT EXISTS '.DB_NAME.';') === TRUE){
  echo "Database successfully created.<br>";
}else{
  echo "Error: ".$mysqli->errno.", ".$mysqli->error."<br>";
}

// DB select
if($mysqli->select_db(DB_NAME) === TRUE){
  echo "Database successfully selected.<br>";
}else{
  echo "Error: ".$mysqli->errno.", ".$mysqli->error;
}

// Create tables
if($mysqli->query(file_get_contents('../sql/tables.sql')) === TRUE){
  echo "Tables successfully created.<br>";
}else{
  echo "Error: ".$mysqli->errno.", ".$mysqli->error."<br>";
}

$mysqli->close();
?>

db\u host、db\u user、db\u password、db\u name在config.php文件中定义
php版本7.4.7

sql表.sql

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `status` (
  `status` varchar(100) NOT NULL,
  `IDtime` varchar(100) NOT NULL
);

如果我使用命令行将这个tables.sql文件直接上传到mysql服务器,它就可以工作了。
mysql v8.0.20 mysql comunity服务器-gpl

错误消息

错误:1064,您的sql语法有错误;检查与mysql服务器版本相对应的手册,以获得在“create table if not exists”附近使用的正确语法 status ( status varchar(100)不为空,`idt'位于第16行

dojqjjoe

dojqjjoe1#

mysqli::query只接受单个查询https://www.php.net/manual/en/mysqli.query.php.
如果要同时执行多个查询,必须使用mysqli::multi\u queryhttps://www.php.net/manual/en/mysqli.multi-query.php.
例子:

$result = $mysqli->query("SELECT * FROM reservations;SELECT * FROM reservations");
var_dump($result, $mysqli->error);

bool(false)
string(172) "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM reservations' at line 1"

$result = $mysqli->multi_query("SELECT * FROM reservations;SELECT * FROM reservations");
var_dump($result, $mysqli->error);

bool(true)
string(0) ""

相关问题