2

I want to use my variables in my mysql queries safely. Im using pdo for this. But i can't use pdo placeholders for table name.

This works;

$stmt = $db->prepare("SELECT * FROM table WHERE id=?");
$stmt->execute(array($id));

But this doesnt;

$stmt = $db->prepare("SELECT * FROM ? WHERE id=?");
$stmt->execute(array($table, $id));

What i'm doing wrong ?

eatik
  • 56
  • 6
  • 2
    You can't use placeholders for table/field names - you already answered that in the question... you need to interpolate them into the string; see : http://stackoverflow.com/questions/8314043/how-to-dynamically-build-queries-with-pdo – CD001 Nov 11 '15 at 10:19

2 Answers2

2

Just do

$stmt = $db->prepare("SELECT * FROM ".$table." WHERE id=?");
$stmt->execute($id);

You can't use placeholders for table

That should not be a problem since the table name should be something you control.

arieljuod
  • 14,762
  • 2
  • 22
  • 34
0

here is the simple answer for you.

$statement = $db->prepare("SELECT * FROM table WHERE id=(:some_id)");
$statement->execute(array(':some_id' => $row['id']));

you should provide it with key => value format.

Kvvaradha
  • 682
  • 12
  • 27