Search code examples
mysqlsqlmysql-error-1054

MySQL prepared statement nvarchar


I have a prepared statement which should update an field.

CREATE PROCEDURE `update_table` (in id INT, in col nvarchar(11), in val nvarchar(10))
BEGIN
SET @sql = concat('UPDATE table SET ', col, ' = ', val , ' WHERE id = ', id);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

If I call the procedure with a string containing a hyphen (e.g. A-B)

CALL update_table(1, 'reg', 'A-B');

I get

Error 1054: Unknown column 'A' in 'field list'

Can you please assist in solving the issue?

Edit: I just figuered out the hyphen is not the cause of error. If I try to update with 'AB', the same error comes up. The field to be updated is nvarchar as well with the same field length.


Solution

  • You're vulnerable to sql injection attacks, basically. Your sproc generated this sql:

    UPDATE ... WHERE reg = A-B
    

    Note the lack of quotes around A-B. You're not storing the string A-B in the reg field. You're doing mathematical subtraction: reg = A minus B, and neither A nor B are fields that exist in your table.

    At BARE minimum you'd need:

    SET @sql = concat('UPDATE table SET ', col, ' = "', val , '" WHERE id = ', id);
                                                    ^----------^
    

    so you're generating

    UPDATE ... reg = "A-B"