简体   繁体   中英

Binding variable for column name in PHP for Postgresql query

I need to dynamically generate the column name I need to update in Postgresql from PHP. Here's the code and the error:

$Col = "dog_".$Num."_pic";
$query_params = array(
        ':user_id_' => $CustomerID,
        'dog_path' => $filePath,
        'dog_col' => $Col)
        ;

$sql = "UPDATE users
        SET 
            `:dog_col`=:dog_path
        WHERE `username`=:user_id_";

I also tried pg_escape_string() with the string.

Here's the error.

"SQLSTATE[42S22]: Column not found: 1054 Unknown column ''dog_1_pic'' in 'field list'"}

You can't bind columns names in your query:

$sql = "UPDATE users 
        SET `:dog_col`=:dog_path
        WHERE `username`=:user_id_";

In this case you must use a variable like this:

    $column = 'myColumn';

    $sql = "UPDATE users
            SET $column = :dog_path
            WHERE username = :user_id_";

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