PDO/MYSQL prepared statements not escaping characters?

倖福魔咒の 提交于 2019-12-11 09:08:19

问题


I'm trying to write power a search function in my program:

$search = "%".$_POST['search']."%";
$query=$connection->prepare("SELECT * FROM TABLE WHERE COLUMN LIKE ?");
$query->execute(array($search));

However, it seems that users can simply enter % and it returns all results. How do I prevent this from happening? I was under the impression that using prepared statements would have escaped these characters. Does this apply to other characters (\, ', etc) as well? How do I fix this?


回答1:


Prepared statements don't escape anything. When you prepare a statement, your query gets precompiled, so that it only needs the placeholders ( ? ) to be filled in. Since theres no way to change the SQL of precompiled query, no escaping is needed.

To fix this, escape % and _ manually.

Added:

A bit of common sense reasoning: In your case, when a user enters % into a searchbox, your $search variable contains string %%%. How would MySQL know, which % it should escape, and which it should leave alone?




回答2:


You'll need to protect against the inclusion of % or _ in your application code if you don't want it as valid input.

if (strpos($_POST['search'], '%') !== FALSE || strpos($_POST['search'], '_') !== FALSE) {
  $query = $connection->prepare("SELECT * FROM TABLE WHERE COLUMN LIKE ?");
  $query->execute(array($search));
}
else echo "% and _ are not allowed!";

As for characters like ', they're treated as part of the string passed in place of the ? placeholder, not concatenated in to build a SQL statement. So they are safe.




回答3:


You must properly escape user input, to let the server know which characters are wildcards, and which are data to match.

$search = '%' . str_replace(array('_', '%'), array('\\_', '\\%'), $_POST['search']) . '%';

This will escape those characters that would otherwise be considered wildcards. $search would now contain something along the lines of:

%100\%%

which will match I always give 100% when working but not I do 100 pushups daily.



来源:https://stackoverflow.com/questions/9181160/pdo-mysql-prepared-statements-not-escaping-characters

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