插入ISO8601 DATETIME会抛出错误


Inserting an ISO8601 DATETIME throws errors

所以我已经尝试了一整天了,我觉得有一个超级简单的解决方案,我只是错过了它。尝试使用此查询:

INSERT INTO codes (`user_id`, `type`, `code`, `expires`) VALUES ($id, $type, $code, $expires);

"expires"的值:

2016-11-13T00:14:43.000Z

查询产生的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':14:43.000Z)' at line 1

数据库结构如下:

CREATE TABLE IF NOT EXISTS codes (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_id` varchar(255) NOT NULL,
`type` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`expires` DATETIME
)ENGINE=InnoDB;

我确实在$expires变量上使用real_escape_string,如果这很重要的话。

谁有什么建议?

您的日期时间值,如2016-11-13T00:14:43.000Z是文本字符串。您需要在insert语句的VALUES子句中将它们用单引号括起来。

实际上,您需要在所有值周围使用单引号,因为它们都是文本字符串。

 INSERT INTO codes (user_id, type, code, expires) VALUES ('$id', '$type', '$code', '$expires');

为了理解这一点,假设您的$code值为143-101。如果你这样做

 INSERT INTO junk (code) VALUES ($code)
在php程序中,MySQL服务器将看到
 INSERT INTO junk (code) VALUES (143-101)

将产生列值42。这会让道格拉斯·亚当斯高兴,但其他人不会。

你想让MySQL服务器看到

 INSERT INTO junk (code) VALUES ('143-101')

,你可以用

 INSERT INTO junk (code) VALUES ('$code')

并且,如果这个应用程序可以访问全球互联网,您必须研究SQL注入并使您的SQL防注入,否则一些网络罪犯 pwn您并窃取您的资产。

相关文章: