且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PDO将撇号添加到mySQL查询中

更新时间:2023-11-30 20:18:28

PDO语句中的占位符仅用于值.如果要将实际SQL添加到查询中,则需要另一种方法.

The placeholders in PDO statements are for values only. If you want to add actual SQL to the query you need to do it another way.

首先,您应该清理$sort并在查询中用反引号将其括起来.

First, you should sanitize $sort and surround it with backticks in the query.

$sort = preg_replace('/^[a-zA-Z0-9_]/', '', $sort);

然后,您可以双引号查询字符串,PHP将用它的值代替$sort:

Then you could double quote the query string and PHP will replace $sort with it's value for you:

$query = "SELECT * FROM table WHERE xxx > 0 ORDER BY `$sort` ASC";

或者您也可以像这样用preg_replace替换它:

Or you could replace it with preg_replace like so:

$query = 'SELECT * FROM table WHERE xxx > 0 ORDER BY `:sort` ASC';
$query = preg_replace('/:sort/', $sort, $query, 1);

我会使用preg_replace方法,因为如果将preg_replace的结果分配给另一个变量而不是覆盖原始变量,它可以让您重用查询.

I would use the preg_replace method because it allows you to reuse the query if you assign the results from preg_replace to another variable instead of overwriting the original variable.