Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Table (FROM) by string

Tags:

php

mysql

Is it possible, to use a dynamic value inside a SELECT FROM sql command?

Database->prepare("SELECT bomb FROM ? WHERE id=?")
    ->execute($strTable,$strID);

result:

Fatal error: Uncaught exception Exception with message Query error: 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...

like image 750
mate64 Avatar asked Dec 22 '11 20:12

mate64


2 Answers

No. The table name cannot be a parameter of the query. You'd need to construct your query string first, concatenating the table name in.

like image 187
Joe Stefanelli Avatar answered Oct 02 '22 17:10

Joe Stefanelli


Assuming $strTable is from a safe source just use

Database->prepare("SELECT bomb FROM $strTable WHERE id=?")
    ->execute($strID);
like image 34
Alex Avatar answered Oct 02 '22 19:10

Alex