簡體   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