Properly escaping fields and query settings when using PDO [duplicate]

无人久伴 提交于 2019-12-13 03:37:19

问题


Possible Duplicate:
How do I use pdo's prepared statement for order by and limit clauses?

I'm using PDO as it has been recommended as the way to go when it comes to PHP database connections. But at the same time I am a obsessed with securing my queries to make sure that my system is as safe as possible from hackers.

PDO and prepared statements is a great way to go, but I have a couple of issues with it. I have a custom filtering system that demands I build a query manually. For example, this:

$query=$pdo->prepare('SELECT * FROM log WHERE username=?');
$result=$query->execute(array($_GET['username']));

This works and everything is great - PDO deals with making sure the $_GET variable does not harm my query.

But what to do when I need to escape other things? For example, if I have this situation, where I want to return just five records:

$query=$pdo->prepare('SELECT * FROM log WHERE username=? LIMIT 5');
$result=$query->execute(array($_GET['username']));

This, again, works. But what if the limit values also come from $_GET? How to escape it?

To do this I first figured that I have to build the query manually and use PDO::quote() method, like this:

$query='SELECT * FROM log WHERE username=? LIMIT '.$pdo->quote($_GET['limit']);

But this did not work, since it placed quotes around the limiter which breaks the query.

Is there a proper way of escaping with PDO the way mysql_real_escape_string() worked? Since the latter never put quotes around the resulting variable, but I'm unable to stop this behavior with quote().

Alternative would be to build my own escaper, but that kind-of defeats the purpose of using PDO prepared statements to begin with (prepared statements themselves always put quotes around values).

EDIT: I also tried casting the value as integer in quote, like this:

$pdo->quote((int)$value,PDO::PARAM_INT);

But it -still- places quotes around it. Same with intval().

Why is PDO so actively suggested and recommended for use if I have to do even primitive things like that custom? I really don't want to write a sanitizing method for cases like this and hope that nothing breaks or is compromised.


回答1:


You are concerned about integer values. As $_GET is always string, you can turn it into an integer with a cast or the %d format of sprintf:

$query = $pdo->prepare(
    'SELECT * FROM log WHERE username=? LIMIT ' . (int) $_GET['page']
);

$query = $pdo->prepare(
    sprintf('SELECT * FROM log WHERE username=? LIMIT %d', $_GET['page'])
);

If you actually need a string, the quote() function you already wrote about is appropriate.




回答2:


This is a great beginner's tutorial. Edumacate thyself.

Why you should be using PHP's PDO...



来源:https://stackoverflow.com/questions/10335069/properly-escaping-fields-and-query-settings-when-using-pdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!