0

Hello Im getting the following error when trying to update my database:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column ''1'' in 'where clause''

Im getting three variables via POST They are:

a) the Column I want to change

b) The new value for the column

c) the ID which row to change...

Im using PDO, this is my Query with param-binding and execution:

$stmt = $db->prepare('UPDATE `artists` SET `:spalte` = `:wert` WHERE  `id` = `:pk` ');
$stmt->bindParam(':spalte', $name);
$stmt->bindParam(':wert', $value);
$stmt->bindParam(':pk', $pk);
$stmt->execute();

I hope someone will understand this error...

Best Regards

Dave

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • Check this [link](http://stackoverflow.com/questions/28477730/why-does-backticks-fails-in-pdo-query) for **Why does backticks fails in PDO query?** – Saty Jul 24 '15 at 13:11
  • 1
    You can only use prepared statement parameters for values, not field names. – Vatev Jul 24 '15 at 13:11
  • Then how can I safely insert the variable as field name? –  Jul 24 '15 at 13:12
  • remove the backticks from your keys in your query; PDO behaves differently. you can leave `artists` but remove them from (for example) `:spalte` and `:wert` – nomistic Jul 24 '15 at 13:16
  • As a simple rule you can not bind the column and table name in prepared statement, and you are using backticks for the placeholder in value section this is also wrong. – Abhik Chakraborty Jul 24 '15 at 13:17
  • also, define the variables before you do the update. You can set them equal to each other in PHP – nomistic Jul 24 '15 at 13:18
  • Removing the Backticks and using sprintf to insert the $name variable worked! –  Jul 24 '15 at 13:20

1 Answers1

0

You can only use prepared statement parameters for values, not field names. – Vatev

Exactly, If you want to put fieldnames from variable then why don't you put that directly in your sql.

This should do the trick.

$stmt = $db->prepare('UPDATE `artists` SET `'.$name.'` = :wert WHERE  `id` = :pk ');

To sanitize column name you could use PDO::quote

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141