gpt4 book ai didi

php - PDO 测试是否连接

转载 作者:行者123 更新时间:2023-11-29 01:06:21 24 4
gpt4 key购买 nike

我在任何地方都找不到这个问题的答案。也许真的很简单

我的 mysql PDO 连接是这样的:

try{
$DBH = new PDO("mysql:host=$db_hostname;dbname=$db_database", $db_username, $db_password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e){
echo $e->getMessage();
exit;
}

我只想测试连接是否有效,即。如果密码、用户名、数据库名和主机名拼写正确。

try, throw 似乎只是找出基本错误,比如驱动程序是否拼写错误。如果说密码错误,它不会抛出错误。

谢谢

最佳答案

单击此问题,在 PDO tag wiki 中在于确切的操作方法:

$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);

还有警告

DO NOT use try..catch operator just to handle an error message.
Uncaught exception already excellent for this purpose, as it will treat PDO errors just the same way as other PHP errors - so, you can define the behavior using site-wide settings. A custom exception handler could be added later, but not required. Especially for new users, it is recommended to use unhandled exceptions, as they are extremely informative, helpful and secure. More info...

关于php - PDO 测试是否连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235881/

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