【问题标题】:How to throw an error with a try catch exception如何使用 try catch 异常抛出错误
【发布时间】:2021-11-30 14:11:33
【问题描述】:

我有一个数据库“用户”,发送来自 html 表单的数据,它包含字段“姓名”、“电子邮件”、“数字”和“日期”,“日期”字段是唯一的,它不能得到两个相同的值,当我尝试发送2个相同的值时,我得到错误:“致命错误:未捕获的PDOException:SQLSTATE [23000]:完整性约束违规:1062重复条目'2021-11-30 00:00:00 ' 为关键 'users.date_visit' "。

我需要使用 try, catch 异常来将此错误作为字符串显示给用户。帮我看看怎么做

向数据库发送值的函数:

public function setData($name, $number, $email, $date)
    {
            $data = [
                'name' => $name,
                'number'=> $number,
                'email' => $email,
                'date' => $date
            ];

            $query = $this->connection->prepare("INSERT INTO Example.users (name, phone_number, email, date_visit)
            values (:name, :number, :email, :date)");

            $query->execute($data);

            return "Information got into the database";
    }
}

【问题讨论】:

  • 您是否阅读了the documentation 并尝试添加 try/catch 块?
  • 我试过所以我决定写在这里
  • 请发布您尝试过的内容。

标签: php pdo


【解决方案1】:

最简单的方法是在$querylike this 中抛出异常

public function setData($name, $number, $email, $date)
    {
            $data = [
                'name' => $name,
                'number'=> $number,
                'email' => $email,
                'date' => $date
            ];

            $query = $this->connection->prepare("INSERT INTO Example.users (name, phone_number, email, date_visit) values (:name, :number, :email, :date)");
            
            if(!$query) die ($this->connection->error);
            
            $query->execute($data);

            return "Information got into the database";
    }
}

这很可能会失败。下一步是添加 $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 到您拨打连接电话的任何地方

然后将代码更改为

public function setData($name, $number, $email, $date)
    {
            $data = [
                'name' => $name,
                'number'=> $number,
                'email' => $email,
                'date' => $date
            ];

            try{
                $query = $this->connection->prepare("INSERT INTO Example.users (name, phone_number, email, date_visit) values (:name, :number, :email, :date)");
                $query->execute($data);
                return "Information got into the database";
            }
            catch (PDOException $error)
            {
                return $error->getMessage();
            }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 2011-03-18
    • 1970-01-01
    相关资源
    最近更新 更多