Home > Database > Mysql Tutorial > body text

Can Prepared Statements Handle Database Identifiers and Keywords?

Linda Hamilton
Release: 2024-11-18 18:46:02
Original
592 people have browsed it

Can Prepared Statements Handle Database Identifiers and Keywords?

Prepared Statements: Can They Handle Identifiers and Keywords?

Dynamic queries utilize variables to specify tables, fields, and search values. While concatenating variables into the query has proven successful, using PDO's bindParam() or bindValue() to bind variables results in empty arrays.

Why It Doesn't Work:

PDO prepared statements only allow placeholders for data literals. Attempting to represent identifiers (table or field names) or keywords using placeholders will not function.

The Solution:

  • Identifiers: To include variables representing identifiers, follow these rules:

    • Enclose identifiers in backticks (`).
    • Escape backticks within the variable by doubling them (``).
  • Keywords:

    • Check user-provided keywords against a whitelist.
    • Use only whitelisted keywords in the query.

Example Code:

// Safely format identifier
$field = "`" . str_replace("`", "``", $field) . "`";
$sql = "SELECT * FROM t ORDER BY $field";

// Whitelist keyword
$dir = $_GET['dir'] == 'DESC' ? 'DESC' : 'ASC';
$sql = "SELECT * FROM t ORDER BY field $dir";
Copy after login

The above is the detailed content of Can Prepared Statements Handle Database Identifiers and Keywords?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template