You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为含LIKE子句的查询正确使用MySQL预处理语句?

Hey, I see where you're stuck with LIKE clauses in mysqli prepared statements—let's fix this step by step!

Your original code has a key issue: you're generating multiple ? placeholders in your SQL, but only passing a single parameter to execute(). Each placeholder needs its own corresponding parameter, and we need to properly format each search term for the LIKE clause.

Here's the corrected, injection-safe code with explanations:

// Clean up input first: trim whitespace and filter out empty terms
$searchInput = strtolower(trim($_POST['e']));
$searchTerms = array_filter(explode(" ", $searchInput));

$sqlConditions = '';
$params = [];

// Build both the SQL conditions and parameter array
foreach ($searchTerms as $term) {
    $sqlConditions .= "AND title LIKE ? ";
    // Wrap each term in % for partial matching, add to params
    $params[] = "%$term%";
}

// Prepare the final query
$stmt = $conn->prepare("SELECT * FROM vdo WHERE 1 $sqlConditions");
// Pass all parameters to execute() (one per placeholder)
$stmt->execute($params);

$found = $stmt->rowCount();
if ($found == 0) {
    echo "NO Results...";
} else {
    // Fetch and process your results here
    while ($row = $stmt->fetch_assoc()) {
        echo htmlspecialchars($row['title']) . "<br>";
    }
}

Key fixes explained:

  • Filter empty terms: array_filter() removes any empty strings from the split input (prevents invalid AND title LIKE ? clauses if the user enters multiple spaces).
  • Parameter array: We build an array of formatted terms (%term%) so each ? placeholder in the SQL gets a matching value. This ensures every search term is properly escaped.
  • Match placeholders to parameters: By passing the full $params array to execute(), mysqli maps each value to its corresponding placeholder, eliminating SQL injection risks entirely.

内容的提问来源于stack exchange,提问作者chetan kurkure

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:46:12