重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
直接使用try...catch....结构。比如:
成都创新互联的客户来自各行各业,为了共同目标,我们在工作上密切配合,从创业型小企业到企事业单位,感谢他们对我们的要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。专业领域包括成都网站设计、成都网站制作、电商网站开发、微信营销、系统平台开发。
try
{
DB::query("SELECT count(*) FROM pre_111 WHERE fid = $fid";
}
catch(exception $ex)
{
echo($ex-getMessage());
}
从Mysql 5.5 开始为我们提供了SIGNAL函数来实现这个功能。
[sql] view plain copy
CREATE TRIGGER `tg_order_create` AFTER INSERT ON `tp_order` FOR EACH ROW BEGIN
DECLARE msg varchar(200);
/*冻结金额*/
IF 2=NEW.condition THEN
UPDATE `tp_user` SET `frozen_amount`=`frozen_amount`+NEW.amount WHERE `id`=NEW.uid AND `amount`-`frozen_amount` NEW.amount;
/*如果余额不足,产生一个错误*/
IF ROW_COUNT() 1 THEN
set msg = "用户余额不足以完成支付.";
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg;
END IF;
/*扣除金额*/
ELSEIF 3=NEW.condition THEN
UPDATE `tp_user` SET `amount`=`amount`-NEW.amount WHERE `id`=NEW.uid AND `amount`-`frozen_amount` NEW.amount;
/*如果余额不足,产生一个错误*/
IF ROW_COUNT() 1 THEN
set msg = "用户余额不足以完成支付.";
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg;
END IF;
END IF;
END;
这里这条触发器的功能是库存操作,当库存足够的时候 减少库存,否则 抛出一个异常并报告商品库存不足:
[sql] view plain copy
CREATE TRIGGER `TG_order_detail_dec_stock` BEFORE INSERT ON `tp_order_detail` FOR EACH ROW BEGIN
DECLARE msg VARCHAR(200);
UPDATE `tp_stock` SET `num`=`num`-NEW.num WHERE `goods_id`=NEW.goods_id AND `mid`=NEW.mid AND `num`=NEW.num;
IF ROW_COUNT() 1 THEN
SELECT CONCAT(`name`, ' 库存不足.') INTO msg FROM `tp_goods` WHERE `id`=NEW.goods_id;
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg;
END IF;
END;
在PHP端的处理(注:使用ThinkPHP框架):
[php] view plain copy
//前面省略若干行....
try {
if (false === ($order_pk = $tbl_order-add($order))) {
$tbl-rollback();
echo json_encode(array('success' = -1, 'message' = "创建订单失败!."), JSON_UNESCAPED_UNICODE);
return;
}
}catch (\PDOException $e){
$errInfo=$e-errorInfo[2];
$tbl-rollback();
echo json_encode(array('success' = -1, 'message' = "创建订单失败!,{$errInfo}"), JSON_UNESCAPED_UNICODE);
return;
}
//后面省略若干行....
user表不存在;而且一般情况下user属于关键字,不应该把user当表名直接用