-1

I'm having trouble with pdo->prepare in mysql, heres the query:

$stmt = $this->pdo->prepare("SELECT * FROM :tabletype where name like :name");

Its parsing as

SELECT * FROM 'type1' where name like 'souza'

its ok with the name string but the tabletype its not working with quotes, is there a way to make it work without the quotes ?

Thanks

ForeverSJC
  • 312
  • 2
  • 4
  • 13

3 Answers3

2

You can only use placeholders where expressions are allowed in the query. Since the tablename is not an expression you can't parametrize it. You have to concatenate the variable explicitly. So it should be:

$this->pdo->prepare("SELECT * FROM `$tabletype` WHERE name LIKE :name");
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Placeholders in prepared statements can only represent VALUES. They cannot be used to replace SQL keywords or table/field names. If you want to use a dynamic table name in your query, you'll have to insert it manually:

$tbl = 'foo';
$dbh->prepare("SELECT * FROM $tbl WHERE field = :placeholder");

And yes, this opens you up to SQL injection attacks. Placeholders are very handy, but they're not universally useful.

And note that if you're doing a LIKE comparison and want to use wildcards, you'll have more work ahead of you:

$dbh->prepare("SELECT * FROM tbl WHERE field LIKE CONCAT('%', :placeholder, '%')");
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Even more so, if the pattern contains one of the two wildcards too: `%` and `_` ... – VMai Aug 21 '14 at 18:39
0

you can not bind table name and column name. use back tick(`) for identifiers like table name, column name etc.

try like this:

$stmt = $this->pdo->prepare("SELECT * FROM `type1` where `name` like :name");
Awlad Liton
  • 9,366
  • 2
  • 27
  • 53