PDO测试如果连接 [英] PDO test if connected

查看:117
本文介绍了PDO测试如果连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找不到答案。也许它真的很简单

I can't find an answer to this anywhere. Maybe its really simple

我有这样的mysql PDO连接:

I have my mysql PDO connection like this:

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;
}

我想测试连接是否正常工作,如果密码,用户名,数据库名&主机名拼写正确。

i want to just test if the connection worked, ie. if the password, username, databasename & hostname were spelled correctly.

尝试,抛出只是似乎拾起基本的错误,如果驱动程序拼写错误。

the try, throw just seems to pick up fundamental errors, like if the driver is spelt wrong. it doesnt throw an error if say the password is wrong.

推荐答案

在此问题的单击中,在 PDO标记维基中找到了精确的操作方法:

In a single click from this question, in the PDO tag wiki lies the exact how-to:

$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);

以及警告


不要使用try..catch 运算符来处理错误消息。

未捕获的异常已经非常适合此目的,因为它会处理PDO错误与其他PHP错误相同的方式 - 因此,您可以使用站点范围的设置定义行为。
以后可以添加自定义异常处理程序,但不是必需的。特别是对于新用户,建议使用未处理的异常,因为它们非常信息丰富,有帮助和安全。
更多信息...

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...

这篇关于PDO测试如果连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆