How to dynamically assign a column name to a query using PHP PDO?

Asked

Viewed 35 times

-1

I’m trying to create a update query, in order to define the column name to be updated dynamically, but for some reason I cannot do this.

Why? And how can I do that?

My current code:

//atualizando ideal
public function inserirIdeal() {
    $teste = $this->coluna->__get('coluna');

    $query = 'update tb_lista set ? = ? where item = ?';
    $stmt = $this->conexao->prepare($query);
    $stmt->bindValue(1, $this->coluna->__get('coluna'));
    $stmt->bindValue(2, $this->ideal->__get('ideal'));  
    $stmt->bindValue(3, $this->item->__get('item'));    

    return  $stmt->execute();
}

Ilustração do problema em código

1 answer

2

Personal as I could not return here I found why I was not getting and I would like to share the answer, so I understood the recommended is that you put the column name, because table and column names CAN NOT be replaced by parameters in the PDO. And so when I put in hardcode it works.

To make this dynamic, as I wanted, you need to put an if condition, check what value comes in that variable, and depending on the value, you call the method that corresponds to that particular column.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.