gpt4 book ai didi

php - 未抛出 PDO 异常

转载 作者:可可西里 更新时间:2023-11-01 12:37:09 26 4
gpt4 key购买 nike

我是 PDO 的新手,关于它的一些事情让我感到困惑,我尝试创建一个测试函数来查看是否会为无效查询抛出异常,但没有抛出任何东西。

这是代码

<?php
include_once("/var/www/include/constants.php");

class DB{
private $DBH;

public function DB(){
try{
$DBH = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}

public function test(){
try{
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$DBH->prepare('DELECT id FROM users');
}
catch(PDOException $e) {
echo $e->getMessage();

}
}

};

/* Create database connection */
$db = new DB;
$db->test();

?>

最佳答案

除了缺少对数据库句柄的 $this 的引用外,您还需要告诉 PDO 它不能模拟准备。下面的代码抛出这样的异常:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELECT id FROM users' at line 1

class DB{
private $DBH;

public function DB(){
try{
$this->DBH = new PDO("mysql:host=localhost;dbname=movies", 'root', 'jsat12');
$this->DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false );
}
catch(PDOException $e) {
echo $e->getMessage();
}
}

public function test(){
try{
$this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->DBH->prepare('DELECT id FROM users');
}
catch(PDOException $e) {
echo $e->getMessage();

}
}

};

/* Create database connection */
$db = new DB;
$db->test();

关于php - 未抛出 PDO 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12872601/

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