1

I want to replace field name with variable to get data from table in PHP and MySQL.

select * from demo where variable-1

instead of select * from demo where fieldname=1

as there are more than 50 fieldname to be chosen from drowpdown.

1
  • You have to use Dynamic Query for your desired Output! Commented Jan 28, 2013 at 5:34

2 Answers 2

5

Variables will not work on field names as well as table Names. The only time it will do is when you are creating dynamic sql, eg

SET @variableName = 'fieldname';
SET @sql = CONCAT('SELECT * FROM demo WHERE `', @variableName, '` = 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't you surround the @variableName with backticks in case it might be a reserved word?
@inhan yes, good point! actually you can alternatively use alias even if's a reserved keyword. :D
@inhan ex, SET @sql = CONCAT('SELECT * FROM demo a WHERE a.', @variableName, ' = 1');
Yeah I almost forgot about that :)
0

You can use 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 ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.