"pdo adds the apostrophe to the mysql query" Code Answer


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.

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

$sort = preg_replace('/^[a-za-z0-9_]/', '', $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";

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

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.

By Adam Hollidge on May 21 2022

Answers related to “pdo adds the apostrophe to the mysql query”

Only authorized users can answer the Search term. Please sign in first, or register a free account.