0

Why do I get a result using this code

$stmt = $users_db->prepare('SELECT * FROM users WHERE user_name = :value');
$stmt->execute([':value' => 'someUser']);
$res = $stmt->fetch();

but not this code?

$stmt = $users_db->prepare('SELECT * FROM users WHERE :field = :value');
$stmt->execute([':field' => 'user_name', ':value' => 'someUser']);
$res = $stmt->fetch();

I know I can work around this by using e.g. 'SELECT * FROM users WHERE ' . $field . ' = :value', but I'd like to know the reason behind not being able to do this. (The reason I need this is because I'm checking if a username or email already exists in the database, hence the need for the variable column name).

cmeeren
  • 3,890
  • 2
  • 20
  • 50
  • Because it's fairly stupid to make user inputs decideable which column decides if a where calusel turns true or not. Also the query gets prepared and the database must know before execution which column is vital and not. If you need to check either one use an if clausel and prepare either one with the right column. Or use OR and ask for both columns. – Charlotte Dunois Aug 16 '15 at 18:53
  • 2
    Please check the answer of this question: http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-name-as-parameter – mario.van.zadel Aug 16 '15 at 18:54

0 Answers0