PDO错误处理 [英] PDO error handling

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

问题描述

从有关intertube的教程中,我学到了一些有关进行PDO查询的知识.本教程使用了try/catch,查询的结构基本上如下:

From a tutorial on the intertubes I learned a bit about doing PDO queries. The tutorial used try/catch and the queries are basically structured like so:

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $user, $pass);

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $stmt = $dbh->prepare("UPDATE users yada yada yadda");

    $stmt->bindParam(':param1', $param1, PDO::PARAM_INT);
    $stmt->bindParam(':param2', $param2, PDO::PARAM_INT);

    $stmt->execute();

}

catch(PDOException $e)
{
    echo $e->getMessage();
}

这当然会在屏幕上回显mysql错误.我并不是要提出错误的查询,但我不喜欢在屏幕上回显错误的想法,弄清楚如果攻击者试图诱使所说的错误并尝试从错误中吸取教训,该怎么办.

This of course echos mysql errors on the screen. Not that I intend on having bad queries, but I do not like the idea of echoing out errors right on the screen, figuring what if an attacker tries to induce said errors and try to learn something from them.

是否有更好的方法来执行此操作,以使任何错误都转至日志文件,或者实际上,由于绑定参数消除了任何SQL注入的风险,因此我实际上不必担心吗?

Is there a better way to do this so that any errors go to a log file instead, or do I in actuality have nothing to fear in this regard since the bound parameters eliminate the risk of any sql injection?

推荐答案

该教程是正确的,因为您想使用try..catch块来捕获可能会导致错误的代码并降低正在加载的内容.因此,如果您有一些依赖于此代码执行的代码,则希望将其包括在try部分中.如果您绝对需要此代码来执行要创建的工作,那么您可能想要捕获错误并将用户重定向到某种类型的错误页面.

The tutorial is correct in that you want to use try..catch blocks to catch code that will possibly cause an error and bring down whatever you're loading. So, if you have some code that is dependent on this code executing you'd want to include it in your try section. If you absolutely need this code to execute for whatever you're creating to work, then you'll probably want to catch the error and redirect the user to some type of error page.

如果您使用 php错误日志功能,那么请使用

If you use the php error log function then instead of

echo $e->getMessage();

您可以使用

error_log($e->getMessage(),0);

将错误消息从PDO直接发送到您的php错误日志.如果您不知道错误日志在哪里,请如果您正在运行* nix系统,则可以查看此链接以获取指向该链接的几个指针.如果您正在运行Windows,则应该在某个位置告诉您配置文件.或者,您可以检查php ini文件所指向的位置,以确保找到日志的方式.

to send the error message from PDO directly to your php error log. If you don't know where the error log is, you can check out this link for a couple pointers to it if you're running a *nix system. If you're running windows there should be a config file somewhere that will tell you. Or you can check the php ini file for the location it's pointing to for a surefire way to find the log.

这篇关于PDO错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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