I am passing table field name as parameter to stored procedure but stored procedure take field name as value instead of field name and throws error.
e.g if i pass value isEnabled via parameter FieldName, Mysql throws error unknown column 'isEnabled' in field list, which shows mysql automatically add quote.
Here is sample stored procedure i wrote.
CREATE `VSK_Comments_UpdateAction`(IN FieldName varchar(30),IN FieldValue tinyint,CID bigint)
BEGIN
Update comments Set FieldName=FieldValue WHERE commentid=CID;
END;
Is there is a way so i can properly pass field name dynamically properly.
You can do this in a couple of ways. One, is to build up the query yourself and execute it. If you opt for that method, be very certain to santise your input.
Create a user-defined table type that corresponds to the table that you want to populate. Pass the user-defined table to the stored procedure as a parameter. Inside the stored procedure, select the data from the passed parameter and insert it into the table that you want to populate.
MySQL Stored Procedures do not provide an array data type. You could implode the php array to a separated string and pass this string as VARCHAR(255) to the stored procedure. Inside the procedure you could split this string back into its elements (see example below).
You can use prepared statements, for example -
CREATE `VSK_Comments_UpdateAction`(IN FieldName varchar(30),IN FieldValue tinyint,CID bigint)
BEGIN
SET @query = CONCAT('Update comments Set ', FieldName, '=? WHERE commentid=?');
PREPARE stmt FROM @query;
SET @FieldValue = FieldValue;
SET @CID = CID;
EXECUTE stmt USING @FieldValue, @CID;
DEALLOCATE PREPARE stmt;
END;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With