简体   繁体   中英

MySql quick user select

I have a Users table and I'm getting user details (usual way) with id.

This is how I'm getting user details;

select id,kullaniciadi,FotoGet(K.Foto,K.Gender) from kullanicilar K where id=1;

FotoGet function always returning string value like 'Photos/ssss.jpg'

So far I have not trouble to use this way but I'm wondering how can I do this with a single function? Like

set @uid=1;
Select UserGet(@uid);

I will put the id inside parentheses and the function will run my select query and return all user detail columns. id , kullaniciadi , FotoGet(K.id,K.Foto,K.Gender)

Can I use this way to get details?

A MySQL stored function cannot return multiple columns, it can only return a single scalar value.

But you could design a stored procedure that returns a result set:

CREATE PROCEDURE UserGet(uid INT)
  SELECT id, kullaniciadi, FotoGet(K.Foto,K.Gender) FROM kullanicilar K WHERE id=uid;

Then call it like so:

CALL UserGet(1234);

It returns a result set just like a SELECT query would.


DELIMITER //

CREATE PROCEDURE UserGet(IN uid INT, IN column_name VARCHAR(64))
BEGIN
  SET @sql = CONCAT('SELECT id, ', column_name, ' FROM kullanicilar K WHERE id=?');
  PREPARE stmt FROM @sql;
  SET @uid = uid;
  EXECUTE stmt USING @uid;
END//

DELIMITER ;

Call it like so:

CALL UserGet(1234, 'kullaniciadi');

Remember that it's your responsibility to write code to pass a valid column name as the procedure argument. If you allow untrustworthy content to be passed, then it might be an SQL injection vulnerability.


Re your additional comment:

This should work fine:

CALL UserGet(1234, 'FotoGet(Foto,Gender)');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM