简体   繁体   English

PDO和MySQL的SQL语法错误,其他地方都没有

[英]SQL Syntax Error with PDO and MySQL, Not Anywhere Else

I created a table in Sequel Pro and exported the create table syntax. 我在Sequel Pro中创建了一个表,并导出了创建表语法。 To my eye, everything looks fine. 在我看来,一切看起来都很好。 The issue is, I'm trying to run the query using PDO and am encountering a syntax error: 问题是,我正在尝试使用PDO运行查询,并且遇到语法错误:

General error: 1 near "UNSIGNED": syntax error

The query works just fine if I run it in Sequel Pro again, or if I run it in PHPMyAdmin. 如果再次在Sequel Pro中运行该查询,或者在PHPMyAdmin中运行该查询,则查询工作正常。 Any clues as to why this query is failing in PDO only? 关于为什么该查询仅在PDO中失败的任何线索?

CREATE TABLE `users` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) UNSIGNED DEFAULT NULL,
  `name` varchar(30) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(60) NOT NULL,
  `passwordResetKey` varchar(8) DEFAULT NULL,
  `activationKey` varchar(8) DEFAULT NULL,
  `permissions` smallint(5) UNSIGNED NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `parent_id` (`parent_id`),
  CONSTRAINT `users_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `users` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Note: I included line breaks above for clarity, but there's no line breaks in the query that's run. 注意:为了清楚起见,我在上面包括了换行符,但是运行的查询中没有换行符。

The code that runs the query: 运行查询的代码:

$query = 'CREATE TABLE `users` ( `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, `parent_id` int(11) UNSIGNED DEFAULT NULL, `name` varchar(30) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(60) NOT NULL, `passwordResetKey` varchar(8) DEFAULT NULL, `activationKey` varchar(8) DEFAULT NULL, `permissions` smallint(5) UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (`id`), KEY `parent_id` (`parent_id`), CONSTRAINT `users_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1';
$statement = $conn->prepare($query);
$statement->execute();

In my case, it turns out that the issue was that I was not properly connecting to the database prior to running the query. 就我而言,事实是问题出在运行查询之前,我没有正确连接到数据库。 The code is for a setup script, so it checked database credentials on a page previous to the page that ran the queries. 该代码用于安装脚本,因此它在运行查询的页面之前的页面上检查了数据库凭据。

However, in the setup pages, the app is setup so that the database must be explicitly connected to (which occurred when I was checking credentials, but not running these queries). 然而,在设置页面中,应用程序是设置,使数据库必须明确地连接(当我被检查凭证,但运行这些查询的发生)。 All I had to do was connect to the database properly, and the queries started functioning. 我要做的就是正确连接到数据库,查询开始起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM