0

I have this bit of code which returns an error, and I can't explain why. Basically I retrieve from GET the table and the id of the post I want to pull from database, and everything works fine as long as the table name is fixed and not :table.
You can clearly see I'm new to PDO, so do you have any thoughts on where I'm doing wrong?

$pageid = $_GET["id"]; //31
$tablename = $_GET["table"]; //table_name
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="SELECT * FROM :table WHERE id LIKE :pageid";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':table', $tablename);
$stmt->bindValue(':pageid', $pageid);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

The error is the following, so appearently the table name is wrapped by ' breaking the script? That seems weird, since the :pageid doesn't have them and the code generating both is the same.

Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table_name' WHERE id LIKE 31' at line 1' in /...

Thanks a lot for any advice

nxet
  • 738
  • 2
  • 10
  • 22
  • exactly what I needed to know, thanks for pointing it out. apologies for the duplicate, should I remove the question? – nxet Nov 23 '15 at 22:07
  • You don't need to delete your question. It is possible that someone has the same problem and cannot find the other question too, but your question. So duplicate questions are OK and only marked as duplicates to prevent duplicate answers. – AbcAeffchen Nov 24 '15 at 17:45

0 Answers0