Reputation: 27
How can i select a table where table name has been stored in a variable.
$a='oop';
I want to refer the table as
select * from '$a';
But this shows error.
What must be the query used instead?
Upvotes: 1
Views: 92
Reputation: 34294
You do not have to enclose $a by single quotes in the query:
$a='oop';
$query="select * from $a";
//then execute the query
You cannot use prepared statements to bind a table name to a variable, so you must use simple string concatenation to assemble such query. Obviously, the assembled query can be executed using a prepared statement, but there is not too much point doing so, unless you have other parameters in your query. This means you have to be extra careful to escape any variables used as table names.
Upvotes: 1
Reputation: 15057
try tihs :-)
SET @tab := 'user';
SELECT CONCAT ('select * from ',@tab,' LIMIT 10') INTO @SQL;
PREPARE stmt FROM @SQL;
EXECUTE stmt;
Upvotes: -1