php - MySQL 查询在 SQL pro 中工作正常,但在 mysqli_query 中工作不正常

标签 php mysql sql database

我尝试了很多方法,但不明白为什么这不起作用...... 基本上,我正在删除并创建表格。以下查询在 SQL PRO 或 mysqladmin 中完美运行

SET foreign_key_checks = 0;

DROP TABLE IF EXISTS `calendarCountries`;

CREATE TABLE `calendarCountries` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `country` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

insert into calendarCountries (id,country) values (1,'US');

DROP TABLE IF EXISTS `calendarWorldHolidays`;

CREATE TABLE `calendarWorldHolidays` (
  `holidayName` varchar(150) NOT NULL,
  `holidayDate` date NOT NULL,
  `countryCode` int(5) DEFAULT NULL,
  KEY `countryCode` (`countryCode`),
  CONSTRAINT `calendarWorldHolidays_ibfk_1` FOREIGN KEY (`countryCode`) REFERENCES `calendarCountries` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

SET foreign_key_checks = 1;

但是每当我尝试通过 php 执行它时,它就不起作用,给我一个语法错误。

我只是像这样将sql语句复制到php

$createTablesQuery = "  <I copy the statements above here>   "
mysqli_query($link, $createTablesQuery)

我得到的错误是:

Invalid query: 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 'DROP TABLE IF EXISTS calendarCountries; CREATE TABLE calendarCountries ( ' at line 3

请帮帮我,我做错了什么?

最佳答案

mysqli_query函数允许仅使用一个查询。如果您需要运行几个查询,则需要为每个查询使用一个 mysqli_query 或使用 mysqli_multi_query功能。例如:

$query1 = "CREATE TABLE `calendarCountries` ( `id` int(5) NOT NULL AUTO_INCREMENT, `country` varchar(50) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;";
$query2 = "insert into calendarCountries (id,country) values (1,'US');";

//Variant 1
mysqli_query($link, $query1);
mysqli_query($link, $query2);

//Variant2
mysqli_multi_query($link, $query1.$query2);

关于php - MySQL 查询在 SQL pro 中工作正常,但在 mysqli_query 中工作不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19349368/

相关文章:

php - 如何将实际的 NULL 值插入到可为空的列中?

MYSQL 仅当行不存在时才从其他表复制

mysql - 对所有列进行编码

PHP SQL 服务器 PDOException :could not find driver

php - 获取所有 PHP session_id 的列表

php - 动态表单提交到数据库

带有德语字母的 PHP 邮件主题

MySQL 计数返回的行数超出应有的行数

sql - PostgreSQL - 分组过滤特定行

php - 让 SQL 从嵌套数组中选择