简体   繁体   中英

Using prepared statements for MySQL query options with PDO

I am using PDO and have options that users can select with their search results. Some examples are sort, number of results, page number, etc. I tried using prepared statements to validate this data to prevent SQL injection attacks, but the variables are never passed into the query.

What am I doing wrong? The sort by and number of results are SELECT menus and the page number is a text input form where they can enter a number.

$query = "SELECT SQL_CALC_FOUND_ROWS * FROM people ORDER BY id :sortBy LIMIT $start, :total";
$result = $conn->prepare($query);
$result->bindValue(":sortBy", $sortBy, PDO::PARAM_STR);
$result->bindValue(":total", $total, PDO::PARAM_INT);

Bound parameters are for actual data you want to pass into the query. You can't bind actual control commands- MySQL will interpret them as data, not as a command.

What you could do instead for your sort by is to check what you're sent, and pass 'ASC' or 'DESC' into the query. You're not passing user provided info to the query- instead, you're using to determine which of a set of predefined commands you are going to pass in. No injection risk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM