首頁 >後端開發 >php教程 >如何使用準備好的語句在 MySQLi 中建立動態 LIKE 條件 SELECT 查詢?

如何使用準備好的語句在 MySQLi 中建立動態 LIKE 條件 SELECT 查詢?

Barbara Streisand
Barbara Streisand原創
2024-12-06 10:48:11572瀏覽

How to Build a Dynamic LIKE Condition SELECT Query in MySQLi Using Prepared Statements?

使用動態LIKE 條件建構SELECT 查詢作為MySQLi 準備語句

問題

使用者可以輸入可變數量的搜尋字詞,並且需要根據這些術語動態建構對應的查詢。目標是建立一個適應此動態輸入的準備好的語句。

解決方案

構造查詢表達式:

將每個搜尋字詞包裝在帶有用於綁定值的佔位符的 LIKE條件(%?).

範例:

$construct .= "name LIKE %?%";

綁定參數:

打包資料類型與輸入值使用splat運算子將其放入一個陣列中(...).

範例:

$parameters = ['sss', '%Bill%', '%N_d%', '%Dave%'];

準備和執行語句:

準備語句使用動態WHERE 子句並綁定參數。

$stmt = $mysqli->prepare('SELECT * FROM info WHERE ' . implode(' OR ', $conditions));
$stmt->bind_param(...$parameters);
$stmt->execute();

擷取結果:

執行查詢並視需要取得結果。

$result = $stmt->get_result();
foreach ($result as $row) {
    echo '<div>' . $row['name'] . '</div>\n'; 
}

範例修正程式碼:

<?php
$string = "my name";
$search_exploded = explode(" ", $string);
$num = count($search_exploded);

$conditions = [];
$parameters = [''];
foreach (array_unique($search_exploded) as $value) {
    $conditions[] = "name LIKE ?";
    $parameters[0] .= 's';
    $parameters[] = "%{$value}%";
}

$query = "SELECT * FROM info";
if ($conditions) {
    $stmt = $mysqli->prepare($query . ' WHERE ' . implode(' OR ', $conditions));
    $stmt->bind_param(...$parameters);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($query);
}
foreach ($result as $row) {
    echo '<div>' . $row['name'] . '</div>\n'; 
}

?>

以上是如何使用準備好的語句在 MySQLi 中建立動態 LIKE 條件 SELECT 查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn