首页 > php中mysql重复插入没有捕获到异常?

php中mysql重复插入没有捕获到异常?

 function sql_add($name,$db_handle)
    {
        try{ 
            $statement = $db_handle->prepare
            (
                'INSERT INTO qiangpiao(name,xuehao,xiaoqu,zuoweihao,time) VALUES (:name,:xuehao,:xiaoqu,:zuoweihao,:time)'
            );
            $number = $db_handle->prepare
            (
                'select count(1) from qiangpiao'  
            );
            $number->execute();
            /*变量的定义*/
            $matches = array();
            $matches = fenci($name);
            $name = $matches[1];
            $xuehao = $matches[2];
            $xiaoqu = $matches[3];
            $zuoweihao = $number->fetch();//通过数据库来增加数据
            echo $zuoweihao[0];
            echo "\n";
            $time = date("Y-m-d H:i:s",time());
            echo $time;

            /*数据绑定*/
            $statement->bindParam(':name',$name);
            $statement->bindParam(':xuehao',$xuehao);
            $statement->bindParam(':xiaoqu',$xiaoqu);
            $statement->bindParam(':zuoweihao',$zuoweihao[0]);
            $statement->bindParam(':time',$time);
            $statement->execute(); 
            return;
        }catch(PODException $e){
            echo $e->getMessage(); 
        }
    }

在数据库中,我设置了主键为学号,重复的话应该会返回一个异常,但我没有捕获到异常,是什么原因,有没有什么解决方法。


默认不把错误当异常抛出,你需要使用 errorCode() 来判断是否执行成功。
你可以设置
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
这样来使得 SQL 执行出错的时候抛出异常。


PODException好像只会在new POD的时候抛出,其他时候都得判断execute()的返回值来确定操作是否成功,并通过errorCode()errorInfo()来获取错误的信息……

【热门文章】
【热门文章】