Question

I just recently started using PDO, not that much experience with it, but I recently crashed into an annoying problem.

I am trying to use bindValue with a fetch statement to retrieve informatie from a database. The variables I get are from a GET, from a previous page. Everything is going wel except for the fact that it is not assigning, I guess, a right value to one of the bindValue.

PDO:

$stmt = $dbconnect->prepare('SELECT * FROM :table WHERE id=:id');

$stmt->bindValue(':table', $table);
$stmt->bindValue(':id', $id);

$stmt->execute();
$row = $stmt->fetch();

I know the difference between bindValue and bindParam. The code is working fine when I hardcode the table value. I have been banging my head against a wall for a short hour now but I can't seem to figure it out. Could anyone beside giving me the correct syntax please explain what went wrong with my thinking because at this point I cannot think of a reason, besides maybe the misinterpretation of the string value, why this is going wrong.

Also for in the future I would like to know the precise content of the SQL command. I tried doing this:

$SQL = 'SELECT * FROM :table WHERE id=:id';
$stmt = $dbconnect->prepare($SQL);

$stmt->bindValue(':table', $table);
$stmt->bindValue(':id', $id);

$stmt->execute();
$row = $stmt->fetch();

But this won't bind the variable values to the SQL variable. Your help is much appreciated!

EDIT: I noticed my post is a duplicate from a FAQ post: FAQ. So my question has been answered however my insight in PDO is not enough to undertand it. Could anyone please explain what happens with the next line of code and why this works, opbtained from the posted link!

$field = "`".str_replace("`","``",$field)."`";
$sql   = "SELECT * FROM t ORDER BY $field";

Answer Thanks to silkfire I came up with fix. Before inserting the SQL string just add the string content into the SQL string:

$SQL = 'SELECT * FROM '.$table.' WHERE id=:id';
Was it helpful?

Solution

PDO does not allow table names or column names to be placeholders. Just create the query with concatenation instead, but make sure the user supplies only valid values. This should be safe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top