Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'"}
like image 997
user1610719 Avatar asked Jul 22 '26 08:07

user1610719


1 Answers

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_";
like image 145
Adrian Cid Almaguer Avatar answered Jul 24 '26 00:07

Adrian Cid Almaguer