我有一张记录库存数量的表格。我设置触发器以在库存变低时警告用户。测试时,触发器会触发,显示消息,但库存不会更新。我做错了什么?是否有另一种设置触发器的方法(不使用SIGNAL SQLSTATE)?我在uWamp中使用phpMyAdmin 4.2.7.1。谢谢你的建议。
触发器代码:
DELIMITER $$
CREATE TRIGGER low_stock_message
AFTER update ON stock_quantity
FOR EACH ROW BEGIN
IF (NEW.Regular_Menu < 50) THEN
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Warning, Regular Menu has a low stock!';
END IF;
IF (NEW.Savers < 50) THEN
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Warning, Savers Menu has a low stock';
END IF;
IF (NEW.Breakfast < 50) THEN
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Warning, Breakfast Menu has a low stock!';
END IF;
END$$
DELIMITER ;
测试查询:
UPDATE stock_quantity
SET Regular_Menu=48
WHERE Outlet_ID=1;
答案 0 :(得分:0)
我怀疑是因为您正在使用SIGNAL SQL STATE '02000'
,according to the documentation是一个异常信号。特别是,“如果函数中的信号未处理,则语句结束。”
答案 1 :(得分:0)
您必须使用sqlstate '45000'
并为此设置message_text
。让我用一个例子解释一下..在下面的例子中,我们的目标是阻止用户投票给自己的帖子,如下所示:
<强>存根强>
create table votes (user_id int);
delimiter //
create trigger prevent_self_votes before insert on votes
for each row
begin
if (new.user_id = 12) then // 12 is id of voter
signal sqlstate '45000' set message_text = 'You cannot vote for yourself, dude!';
end if;
end //
delimiter ;
PHP脚本
<?php
$db = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$sql = 'insert into votes values (:user_id)';
$statement = $db->prepare($sql);
if ($statement === false) {
echo 'statement is false';
exit();
}
try {
$result = $statement->execute(array(':user_id'=>12));
if ($result === false) {
$error = $statement->errorInfo();
print_r($error);
echo "$error[2] ... is the error reported by trigger\n";
}
else {
print_r($result);
echo 'Inserted', "\n";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>
<强>结果强>
$ php test.php
Array
(
[0] => 45000
[1] => 1644
[2] => You cannot vote for yourself, dude!
)
You cannot vote for yourself, dude! ... is the error reported by trigger
如您所见,您可以使用$statement->errorInfo()[2]
的输出来提取触发器提供的信息。
http://php.net/manual/en/pdo.errorinfo.php表示数组中的第一项是SQLSTATE ANSI SQL错误代码,第二项是驱动程序特定的错误代码,第三项是驱动程序特定的错误消息。