我已经被困在这里大约30分钟,我不知道我是否可以忽略任何东西,但我一直收到以下错误(主要是因为我的SQL无效):
致命错误:在非对象上调用成员函数bind_param()...
SQL:
IF (SELECT value FROM votes WHERE thread = ? AND owner = ?) THEN
UPDATE votes SET (value = ?) WHERE thread = ? AND owner = ?
ELSE
INSERT INTO votes (thread, owner, value) VALUES (?, ?, ?)
END IF
PHP:
$stmt = $this->database->prepare("IF (SELECT value FROM votes WHERE thread = ? AND owner = ?) THEN UPDATE votes SET (value = ?) WHERE thread = ? AND owner = ? ELSE INSERT INTO votes (thread, owner, value) VALUES (?, ?, ?) END IF");
$stmt->bind_param("dddddddd", $this->id, $userId, $value, $this->id, $userId, $this->id, $userId, $value);
$stmt->execute();
根据MySQL文档,我应该是正确的吗?
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
答案 0 :(得分:4)
IF
语句仅适用于编程块 - 存储过程,函数和触发器。
您可以使用on duplicate key update
执行所需操作:
INSERT INTO votes (thread, owner, value)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE value = VALUES(value);
为此,您应在thread
/ owner
上定义唯一键/约束:
create unique index unq_votes_thread_owner on votes(thread, owner);
答案 1 :(得分:2)
不,你不能这样做。
您引用的if
syntax用于存储过程/函数(而不用于查询)。
您可以使用两个不同的查询: