[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
}
//后面省略若干行....
之前还以为从上至下统一用上UTF-8就高枕无忧了,哪知道今天在抓取新浪微博的数据的时候还是遇到字符的异常。从新浪微博抓到的数据在入库的时候抛出异常:
Incorrect
string
value:
'\xF0\x90\x8D\x83\xF0\x90...'
发现导致异常的字符不是繁体而是某种佛经文字。。。额滴神。。。但是按道理UTF-8应该能支持才对啊,他不是万能的么?
原来问题出在mysql上,mysql如果设置编码集为utf8那么它最多只能支持到3个字节的UTF-8编码,而4个字节的UTF-8字符还是存在的,这样一来如果你建表的时候用的utf8字符集出异常就理所当然了。
解决方法很简单,修改字段或者表的字符集为utf8mb4。
比较蛋疼的是,字符集utf8mb4在mysql
5.5.3之后才支持。
直接使用try...catch....结构。比如:try
{
DB::query("SELECT count(*) FROM pre_111 WHERE fid = $fid"
}
catch(exception $ex)
{
echo($ex->getMessage())
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)