2015-10-16 71 views
1

我检查了多个PDO帖子,他们都说这个语法不正确,但即使在检查时我似乎无法找到它。 这里是我的代码:PDO重复更新错误

$stmt = $pDatabase->prepare('INSERT INTO Agenda (index, date, shortdesc) VALUES :values ON DUPLICATE KEY UPDATE date=VALUES(date), shortdesc=VALUES(shortdesc)'); 

我试图在最后一个;修复它,或者在一次插入一个。它准备上的错误,所以无论:values应该甚至不重要。

这是产生的误差:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'index, date, shortdesc) VALUES(?, ?, ?)ON DUPLICATE KEY UPDATE date=VALUES(date)' at line 1' in /customers/f/b/e/**************/httpd.www/editagenda.php:14 Stack trace: #0 /customers/f/b/e/**************/httpd.www/editagenda.php(14): PDO->prepare('INSERT INTO Age...') #1 {main} thrown in /customers/f/b/e/**************/httpd.www/editagenda.php on line 14

其中14是prepare线。

此行在DBadmin中正常工作。

我的表看起来像这样:

index  date   shortdesc  longdesc   boolean 
10   2015-12-12 Something  copyshort   1 
11   2015-11-12 Somethi2ng  copyshort2   0 
+0

错误消息中的SQL与您发布的SQL不同。 '$ stmt'中没有'VALUES(?,?,?)'。 – Barmar

回答

5

不能使用一个占位符,这样的多个值。

the manual

Note: Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters. For example, you cannot bind multiple values to a single parameter in the IN() clause of an SQL statement.

试试这个:

$stmt = $pDatabase->prepare('INSERT INTO Agenda (index, date, shortdesc) VALUES (:index, :date, :shortdesc) ON DUPLICATE KEY UPDATE date=VALUES(date), shortdesc=VALUES(shortdesc)'); 

(请注意,您所需要的())然后通过三个值,每一个占位符(:index:date,和:shortdesc)。

P.S.请注意,indexdate在MySQL(和大多数RDBMS)中是reserved words。您需要将它们包装在背包中,如下所示:

$stmt = $pDatabase->prepare('INSERT INTO Agenda (`index`, `date`, shortdesc) VALUES (:index, :date, :shortdesc) ON DUPLICATE KEY UPDATE date=VALUES(`date`), shortdesc=VALUES(shortdesc)'); 
+0

那么..如果我想要根据变量(count)添加可变数量的值,该怎么办?我仍然必须做一个循环并不断添加一个新的(:index,:date,:desc),(:index2,:date2:desc2)等?这完全违背了使用参数标记的目的,也可能直接将它们插入到查询中,以供我使用它。 –

+0

@JordyBrinks准确。你总是可以创建一个包装类(例如[装饰器](https://en.wikipedia.org/wiki/Decorator_pattern))来为你自动化循环。 –

+0

@JordyBrinks请参阅我上面的修改;我只注意到一个额外的问题,这是造成您的原始错误。 –