Home >Backend Development >PHP Tutorial >Can PHP PDO Prepared Statements Use Parameters for Table or Column Names?

Can PHP PDO Prepared Statements Use Parameters for Table or Column Names?

DDD
DDDOriginal
2025-01-03 07:33:40485browse

Can PHP PDO Prepared Statements Use Parameters for Table or Column Names?

Can Parameters Substitute Table or Column Names in PHP PDO Statements?

It is impossible to pass table names as parameters to prepared PDO statements. Consider the following code that attempts to do so:

$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');
if ($stmt->execute(array(':table' => 'users'))) {
    var_dump($stmt->fetchAll());
}

This approach will result in an error, as table and column names cannot be replaced by parameters.

Safe Insertion of Table Names into SQL Queries

To safely insert table names into SQL queries, an alternative approach is necessary. Avoid directly inputting user input into the query, such as:

$sql = "SELECT * FROM $table WHERE 1"

Instead, consider filtering and sanitizing the input. One method involves passing shorthand parameters to a function that will dynamically execute the query. A switch() statement can then be employed to whitelist valid table names. For example:

function buildQuery( $get_var ) 
{
    switch($get_var)
    {
        case 1:
            $tbl = 'users';
            break;
    }

    $sql = "SELECT * FROM $tbl";
}

By omitting a default case or using one that displays an error message, you guarantee that only desired values will be utilized.

The above is the detailed content of Can PHP PDO Prepared Statements Use Parameters for Table or Column Names?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:PHP OOP Part-PolymorphismNext article:PHP OOP Part-Polymorphism