簡體   English   中英

MySQL中的PHP循環和綁定查詢

[英]PHP loops and binding queries in MySQL

上下文

我正在嘗試使用PHP和MySQL編寫有效且安全的搜索腳本,這將防止SQL注入嘗試。 我正在使用MySQLi函數套件,並且專門將用戶輸入綁定到數據庫查詢。 因為用戶可能一次搜索多個單詞,所以我開發了一種將變量動態綁定到MySQLi查詢的方法,但是卻被困在一個特定的位置。

我有一個示例用戶表和一個用戶具有的所有技能的表:

USERS:               SKILLS:
ID | Username        Userid  | Skill
1  | Patty           1       | Decorating
2  | Billy           1       | Renovating
                     2       | Painting
                     2       | Flooring

我產生了一個搜索查詢,該查詢將分解訪客已搜索的所有搜索詞,然后通過MYSQLi查詢運行它們:

$searched = explode (' ', stripslashes ($search)); // What the visitor searched for

$bindParam = new BindParam (); // Initiate the dynamic binding class
$qArray = array (); 

foreach ($searched as $sd) {    
    $sd = trim ($sd);   
    if ($sd != '') {
        $qArray[] = 'skills.skill LIKE CONCAT(?,\'%\')'; // Use arrays to construct part of the dynamic query
        $bindParam->add ('s', $sd); // Users are searching for strings so use 's' as opposed to 'i' for integer for example
    }
}

$query = "SELECT username FROM users WHERE users.id IN (SELECT skills.userid FROM skills WHERE ";
$query .= implode (' OR ', $qArray);
$query .= ")"; // Join the query together

$stmt = $mysqli->prepare ($query) or die ("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);    
call_user_func_array (array ($stmt, "bind_param"), $bindParam->get ()); // Bind the variables to the query

$stmt->execute ();
$stmt->store_result ();

if ($stmt->num_rows > 0) {              
    $stmt->bind_result ($username);
    $searchoutput = array ();
    while ($stmt->fetch ()) {
        $searchoutput[] = $username; // send all usernames to an array      
    }

print_r ($searchoutput); // print all contents of the array

}

問題

現在,當訪客搜索“裝飾裝修畫”時 ,代碼將返回:

Array ( [0] => patsy [1] => billy )

...因為MySQL查詢實際上忽略了Patsy出現兩次的事實。 理想情況下,我希望數組實際顯示:

Array ( [0] => patsy [1] => patsy [2] => billy )

除非我根據搜索詞的數量將查詢合並到循環中,否則如何解決此問題?

而不是子查詢,我建議加入:

SELECT username FROM users 
JOIN skills ON users.id=skills.userid
WHERE
skills.skill LIKE CONCAT(?,\'%\')
OR skills.skill LIKE CONCAT(?,\'%\')
OR ...

當他們在多種技能上匹配時,應該多次顯示用戶名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM