gpt4 book ai didi

php - 为什么我不能用 PDOException 捕获错误?

转载 作者:行者123 更新时间:2023-11-30 21:35:37 26 4
gpt4 key购买 nike

获取POST传递过来的信息,将字符串中的所有空格去掉,然后启动一个新的pdo实例,连接mysql,将POST传递过来的信息插入到表中。

$title = trim($_POST["title"]);
$content = trim($_POST["content"]);

$dsn = "mysql:host=localhost;dbname=blog";
$con = new PDO($dsn,"root","xxxx");

$title = $con->quote($title);
$content = $con->quote($content);

try
{
$sql = "insert into tmp (`title`,`content`) values('$title','$content')";
$stmt = $con->prepare($sql);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}

上面是我完成工作的PHP代码,最重要的命令是

insert into tmp (`title`,`content`) values('$title','$content')";

运行上述 PHP 代码没有显示错误信息,/var/log/mysql/error.log 中也没有错误,但是信息还没有插入到数据库中。

我改变了

insert into tmp (`title`,`content`) values('$title','$content')";

进入

insert into tmp (`title`,`content`) values($title,$content)";

现在POST传过来的信息可以插入到mysql中了,我比较困惑的问题是:

  1. echo $e->getMessage(); 完全没有效果。
  2. /var/log/mysql/error.log 中没有错误信息

我怎样才能捕捉到这些错误?

最佳答案

你试图捕获的异常永远不会被抛出,因为你需要 to tell PDO how you want it to handle errors .

$con = new PDO($dsn,"root","xxxx");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

否则,将使用默认的PDO::ERRMODE_SILENT:

This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.

切线地,你应该使用 prepared statements .您正在使用 prepare() 调用,但您没有按应有的方式参数化查询和绑定(bind)变量。使用 quote() 不够安全。


2020 年更新:

有趣的是,从 PHP 8 开始,PDO 的默认行为将发生变化,默认情况下会抛出异常。更改在 this RFC 上投票,其中提到:

The current default error mode for PDO is silent. This means that when an SQL error occurs, no errors or warnings may be emitted and no exceptions thrown unless the developer implements their own explicit error handling.

This causes issues for new developers because the only errors they often see from PDO code are knock-on errors such as “call to fetch() on non-object” - there's no indication that the SQL query (or other action) failed or why.

2020 年 11 月发布 PHP 8 时,默认错误模式将为 PDO::ERRMODE_EXCEPTION

关于php - 为什么我不能用 PDOException 捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com