如何为含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 invalidAND 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
$paramsarray toexecute(), mysqli maps each value to its corresponding placeholder, eliminating SQL injection risks entirely.
内容的提问来源于stack exchange,提问作者chetan kurkure
相关产品推荐
相关产品推荐

