如何使用变量名选择表名

时间:2022-09-21 00:41:32

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?

使用的查询必须是什么?

3 个解决方案

#1


1  

Try this:

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

#2


1  

You do not have to enclose $a by single quotes in the query:

您不必在查询中用单引号括起$ a:

$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.

您不能使用预准备语句将表名绑定到变量,因此必须使用简单的字符串连接来组合此类查询。显然,汇编后的查询可以使用预处理语句执行,但除非您的查询中有其他参数,否则没有太多意义。这意味着您必须格外小心地转义用作表名的任何变量。

#3


-1  

try tihs :-)

试试看:-)

SET @tab := 'user';

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

PREPARE stmt FROM @SQL;
EXECUTE  stmt;

#1


1  

Try this:

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

#2


1  

You do not have to enclose $a by single quotes in the query:

您不必在查询中用单引号括起$ a:

$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.

您不能使用预准备语句将表名绑定到变量,因此必须使用简单的字符串连接来组合此类查询。显然,汇编后的查询可以使用预处理语句执行,但除非您的查询中有其他参数,否则没有太多意义。这意味着您必须格外小心地转义用作表名的任何变量。

#3


-1  

try tihs :-)

试试看:-)

SET @tab := 'user';

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

PREPARE stmt FROM @SQL;
EXECUTE  stmt;