1

So I was wondering why this prepared statment would not work

$makr = 'users';
$stm = $con->prepare("SELECT * FROM ?");
$stm->bindparam(1, $makr);
$stm->execute();

I keep getting this error.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dd23834_house.'users'' doesn't exist' in /nfs/c11/h05/utt/23824/domains/.../html/home.php:77 Stack trace: #0 /nfs/c11/h05/utt/23824/domains/.../html/home.php(77): PDOStatement->execute() #1 {main} thrown in /nfs/c11/h05/utt/23824/domains/.../html/home.php on line 77

Yes I do have a table named Users.

I only want to grab everything from the users DB, I do NOT have a where clause in that but I also want it to be secure.

Kmiles1990123
  • 189
  • 2
  • 12
  • You can't bind a table/colum `FROM ?` and closed respectively. – Funk Forty Niner Mar 02 '16 at 14:33
  • Ok, Thanks I did not know that. I tried to find it on my own but couldnt not find a post like the one that you linked. Thanks again. – Kmiles1990123 Mar 02 '16 at 14:37
  • You're welcome. You can use a safelist, in regards to a comment you left in an answer below. – Funk Forty Niner Mar 02 '16 at 14:38
  • I will need to look up what that is exactly cause I am not sure. Would it be something like this `function buildQuery( $get_var ) { switch($get_var) { case 1: $makr = 'users'; break; } $stm = $con->prepare("SELECT * FROM $makr"); $stm->execute(); }` – Kmiles1990123 Mar 02 '16 at 14:41
  • I saw something like that on the post you linked – Kmiles1990123 Mar 02 '16 at 14:41
  • You don't need such a function. In reality you will never need a query like "SELECT * FROM table". – Your Common Sense Mar 02 '16 at 14:43
  • But this is reality and I do need that function. How do you think it should be written to be the most secure. What exactly is a safelist. I just keep finding things about paypal safelist scripts. The reason I need that function is because I have a table that will display all user data from that USERS table. So I do not need a where clause there. – Kmiles1990123 Mar 02 '16 at 14:46
  • Use the term [whitelist](http://stackoverflow.com/questions/12887696/safely-escaping-table-names-column-names) instead of safelist. – Jay Blanchard Mar 02 '16 at 14:59
  • Perfect!! Thanks man – Kmiles1990123 Mar 02 '16 at 15:15

1 Answers1

1

Table and Column names cannot be replaced by parameters in PDO. What you can do is:

$makr = 'users';
$stm = $con->prepare("SELECT * FROM $makr");
$stm->execute();
Daan
  • 12,099
  • 6
  • 34
  • 51