user6188663
user6188663

Reputation: 27

how to select a table name using a variable name

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

Answers (3)

Shadow
Shadow

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

JYoThI
JYoThI

Reputation: 12085

Try this:

$a='oop'; $query='select * from '.$a;

Upvotes: 1

Bernd Buffen
Bernd Buffen

Reputation: 15057

try tihs :-)

SET @tab := 'user';

SELECT CONCAT ('select * from ',@tab,' LIMIT 10') INTO @SQL;

PREPARE stmt FROM @SQL;
EXECUTE  stmt;

Upvotes: -1

Related Questions