Skip to content
Advertisement

How to access a table using a variable name in sql query

I have multiple tables in my database named teacher1, teacher2…. I am trying to access them using a variable $id.

I have written down the following code.

$query = "SELECT * FROM table.$id";  

How could i access those different tables using a variable.

Advertisement

Answer

I’m not clear from the question text whether your $id variable contains the full table name, or some kind of number.

However, in either case you have to make a slight tweak to your $query variable.

If $id contains the full name of the table (i.e. teacher1):

$query = "SELECT * FROM " . $id;

If $id contains a number used to identify which teacher table it is (i.e. 1, 2, 3, etc):

$query = "SELECT * FROM teacher" . $id;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement