在存储过程中使用LIKE并同时转义注入

时间:2013-12-17 22:15:04

标签: mysql sql stored-procedures escaping code-injection

所以我在MySQL中有一个存储过程

delimiter //
DROP PROCEDURE IF EXISTS mysearch;

CREATE PROCEDURE mysearch (IN term varchar(255), IN brands varchar(512), IN categories varchar(512), IN priceRange varchar(32))
BEGIN
  SET @query = 'SELECT name, price, image FROM (... join some tables here ... ) WHERE (... prod.category = some number ...)';

  IF (term IS NOT NULL) THEN
    SET term = CONCAT('\'%',term,'%\'');
    SET @query = CONCAT(@query, ' AND (prod.name LIKE ', QUOTE(term), ' OR prod.number LIKE ', QUOTE(term), ')');
  END IF;
  PREPARE stmt1 FROM @query;

  EXECUTE stmt1;
END //
delimiter ;

我如何使用LIKE并仍然逃避用户输入?

我想清理用户输入,但仍允许使用LIKE进行搜索。

2 个答案:

答案 0 :(得分:1)

您可以使用PREPARE语句执行此操作。 有一个例子here

答案 1 :(得分:1)

也许是这样的

DROP PROCEDURE IF EXISTS mysearch;

CREATE PROCEDURE mysearch (IN term varchar(255), IN brands varchar(512), IN categories varchar(512), IN priceRange varchar(32))
BEGIN
  DECLARE fullterm varchar(255);
  SET fullterm = CONCAT('%',term,'%');

  SELECT name, price, image FROM (... join some tables here ... ) WHERE (... prod.category = some number ...)
  AND (term IS NULL OR (prod.name LIKE fullterm OR prod.number LIKE fullterm));
END

演示 http://sqlfiddle.com/#!2/a5e50/9