如何使用SQLSTATE';45000';PHP中的消息文本?
我有这样一个触发器:如何使用SQLSTATE';45000';PHP中的消息文本?,php,mysql,sql,Php,Mysql,Sql,我有这样一个触发器: CREATE TRIGGER prevent_self_votes BEFORE INSERT ON votes FOR EACH ROW BEGIN IF(new.user_id = (SELECT author_id FROM posts WHERE id=new.post_id)) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot vote for yours
CREATE TRIGGER prevent_self_votes BEFORE INSERT ON votes
FOR EACH ROW
BEGIN
IF(new.user_id = (SELECT author_id FROM posts WHERE id=new.post_id)) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot vote for yourself";
END IF;
END;
现在我想知道,我如何使用PHP中的文本您不能为自己投票
注意:我使用PDO。如果您的查询失败,请检查导致失败的原因,查看的定义 您可以执行try…catch并检查语句执行的结果,以打印如下错误信息:
CREATE TRIGGER prevent_self_votes BEFORE INSERT ON votes
FOR EACH ROW
BEGIN
IF(new.user_id = (SELECT author_id FROM posts WHERE id=new.post_id)) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot vote for yourself";
END IF;
END;
存根
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
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]
的输出来提取触发器提供的信息
表示数组中的第一项是SQLSTATE ANSI SQL错误代码,第二项是特定于驱动程序的错误代码,第三项是特定于驱动程序的错误消息