MySQL - 使用准备语句在存储过程中传递动态列名

时间:2014-09-11 14:33:16

标签: php mysql sql

在过去的12个小时里,我一直把头发拉过来。我正在尝试创建一个存储过程来显示PHP页面中的搜索结果。有几个列名称是动态的,并由php页面传入。我以为我可以使用准备好的声明解决这个问题,但它似乎没有用。当我在phpMyAdmin中运行下面的SP时,我得到零行返回。

CREATE DEFINER=`test`@`localhost` PROCEDURE `AllLoads7`( 
        IN p_search_field VARCHAR(25), 
        IN p_search_for VARCHAR(250), 
        IN p_load_status INT, 
        IN p_date_field VARCHAR(25), 
        IN p_startDate DATETIME, 
        IN p_endDate DATETIME, 
        IN p_employeeID INT,
        IN p_OrderBy VARCHAR(25)
    )
begin
SET @GetLoads = CONCAT("SELECT * FROM loads_contacts WHERE ",p_search_field," LIKE '%",p_search_for,"%' AND status LIKE '%",p_load_status,"%' AND ",p_date_field," BETWEEN '",p_startDate,"' AND '",p_endDate,"' AND company_id IN(SELECT company_id FROM employees_companies WHERE employee_id = ",p_employeeID,") ORDER BY ",p_OrderBy);
PREPARE stmt FROM @GetLoads;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end

这是phpMyAdmin如何调用它

SET @p0='pronumber'; 
SET @p1='1'; 
SET @p2='1'; 
SET @p3='dateCreated'; 
SET @p4='2010-01-01'; 
SET @p5='2014-01-01'; 
SET @p6='2'; 
SET @p7='status'; 

CALL `AllLoads7`(@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7);

如果我添加“SELECT @GetLoads;”到SP,我得到以下查询。如果我对我的数据库运行该查询,我得到返回的预期行。这告诉我SQL正在正确生成,似乎我没有做正确执行准备语句的事情

@GetLoads
SELECT * FROM loads_contacts WHERE pronumber LIKE '%1%' AND status LIKE '%1%' AND dateCreated BETWEEN '2010-01-01 00:00:00' AND '2014-01-01 00:00:00' AND company_id IN(SELECT company_id FROM employees_companies WHERE employee_id = 2) ORDER BY status

0 个答案:

没有答案