Research question on multi-column query using PHP
P粉242126786
2023-07-26 17:32:50
<p>I have a question. I need to query all text containing a substring given by using POST method on PHP. For example, if I enter an "a" or a number like "1" (a character not an integer), do I need to find everything that contains that character or substring and check every column in the table if that's possible? I've tried something like this, but the code is a bit messy. </p>
<pre class="brush:php;toolbar:false;"><?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$usersearch = $_POST["usersearch"];
try {
require_once "includes/dbh.inc.php";
$query = "SELECT * FROM tlattine WHERE
tipologia LIKE :usersearch OR
nome LIKE :usersearch OR
caratteristiche LIKE :usersearch OR
tabstyle LIKE :usersearch OR
tabcolor LIKE :usersearch OR
topstyle LIKE :usersearch OR
topcolor LIKE :usersearch OR
provenienza LIKE :usersearch OR
produttore LIKE :usersearch OR
sku LIKE :usersearch
ORDER BY tipologia, provenienza, year, dimensione;";
$stmt = $pdo->prepare($query);
$stmt->bindParam(":usersearch", $usersearch);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$pdo = null;
$stmt = null;
} catch (PDOException $e) {
die("Query failed: " . $e->getMessage());
}
}
else{
header("Location: ../index.php");
}
?></pre>
<p>Already tried using '%:usersearch%' or combining % in any form but it seems I'm missing something, I'm absolutely sure but I can't find it :(</p>
Seeing your query, I noticed that you used the parameter: usersearch multiple times.
Mentioned in the PHP documentation:
I prefer to avoid enabling impersonation mode and instead change named placeholders to positional placeholders (use '?' instead of ':usersearch') , then use
One last thing, if you are querying so that the column contains the $usersearch variable, you should probably add % at the beginning and end of the string.