mysql field name from variable

If the string is in your external application (like PHP), sure, just construct the MySQL statement.

If the string is inside a MySQL table, you can’t. MySQL has no eval() or such function. The following is impossible:

Suppose you have a table queries with a field columnname that refers to one of the column names in the table mytable. There might be additional columns in queries that allow you to select the columnname you want.

INSERT INTO queries  (columname) VALUES ("name")
SELECT (select columnname from queries) from mytable

You can however work with PREPARED STATEMENTS. Be aware this is very hacky.

SELECT columnname from queries into @colname;
SET @table="mytable";
SET @s = CONCAT('SELECT ',@colname,' FROM ', @table);

PREPARE stmt FROM @s;
EXECUTE stmt;

Leave a Comment