繁体   English   中英

WHERE子句的动态PDO参数绑定问题

[英]Dynamic PDO parameter binding issue with WHERE clause

我有一个搜索表单,用户可以在其中输入一些信息来搜索数据库中的记录。 由于某些字段可以留空,因此,我正在动态创建查询的WHERE子句以及动态绑定PDO参数。 如果用户仅在搜索表单中填写1个字段,则一切工作都很好,但是如果使用多个字段,则返回一个空数组。 这是我的代码。

if(count($_POST)>0)
{   
    //Remove any key that has no value  
    $data = array_filter($_POST);

    //Define array to hold the pieces of the where clause
    $where = array();

    //loop each of the variable to build the query
    foreach($data as $key=>$value)
    {
        $key = mysql_real_escape_string($key);

        //Push values to array
        array_push($where, "$key=:$key");
    }

    //Create the select query
        $query = "SELECT application_ID, 
                     student_last_name, 
                     student_first_name,
                     s.school_name,
                     DATE_FORMAT(submission_datetime, '%m/%d/%Y %h:%i:%s %p') AS  submission_datetime, 
                     aps.name  
                     FROM application a
                     LEFT JOIN application_status aps ON(aps.status_ID = a.application_status_ID)
                     LEFT JOIN schools s ON(s.school_ID = a.school_choice)";
    //As long as criteria was selected in the search form then add the where clause to the query with user's search criteria
    if(!empty($where))
    {       
        $query .= "WHERE ".implode(" AND ", $where);
    }

    //Add ORDER BY clause to the query
    $query .= " ORDER BY application_ID";

    $stmt = $conn->prepare($query);
    //loop each of the variables to bind parameters
    foreach($data as $key=>$value)
        {
            $value = mysql_real_escape_string($value);
            $stmt->bindparam(':'.$key, $value);
        }
    $stmt->execute();
    $result = $stmt->fetchall(PDO::FETCH_ASSOC);


}

当我回显查询时,从PHPMyAdmin运行时,一切看起来都很好,甚至返回结果。 这是查询。

SELECT application_ID, 
       student_last_name, 
       student_first_name, 
       s.school_name, 
       DATE_FORMAT(submission_datetime, '%m/%d/%Y %h:%i:%s %p') AS submission_datetime,
       aps.name 
       FROM application a 
       LEFT JOIN application_status aps ON(aps.status_ID = a.application_status_ID)
       LEFT JOIN schools s ON(s.school_ID = a.school_choice)
       WHERE school_choice=:school_choice AND status_ID=:status_ID 
       ORDER BY application_ID ASC

当我print_r我得到一个空数组。 感谢您的任何帮助,您可以提供。

当您遍历数组以将值绑定到PDO语句时,应使用bindValue而不是bindParam。

当您说$stmt->bindparam(':'.$key, $value) ,查询将使用查询执行时的变量$value $value将是数组的最后一个元素。

http://php.net/manual/en/pdostatement.bindvalue.php

我希望这有帮助。

您不应该将mysql_real_escape_string()与已准备好的语句一起使用。 实际上,如果您没有初始化mysql_connect() ,那么该函数将不起作用。

这一定是为什么这一切都会失败的原因,您对mysql_real_escape_string()调用对所有内容均返回FALSE

另外,是什么使您认为来自$_POST数组键可以安全地用于SQL查询中? 您在这里冒着严重的SQL注入风险,请不要这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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