我想用变量替换字段名来从PHP和MySQL中的表中获取数据。
select * from demo where variable-1
而不是select * from demo where fieldname=1
因为从drowpdown中选择了超过50个fieldname。
答案 0 :(得分:5)
field names
以及table Names
上变量不起作用。它唯一能做的就是创建动态sql ,例如
SET @variableName = 'fieldname';
SET @sql = CONCAT('SELECT * FROM demo WHERE `', @variableName, '` = 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
答案 1 :(得分:0)
您可以使用Prepared Statements
delimiter //
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
PREPARE stmt FROM @s;
EXECUTE stmt;
END
//
delimiter ;