I am making a site that has an autocomplete product search bar. When a user types in a few letters, I compare them to the database with the LIKE statement and get products back that look similar. A user can see a max of 4 products that the user was thinking of in a drop down under the search bar. Now once the user clicks on a result, I pass that back to the PHP PDO statement.
If the product doesn't contain a %
, it works fine. But I have products such as '100% Product A', and I can't seem to get around it. I know % is used in the LIKE statement. I used like, but the results weren't great. I was getting a different variation of the product I wanted. How do I get passed this?
$pdo = new PDO($dsn, $user, $passwd);
//Retrieving Product Name
$prodName = $_GET['name'];
$stm = $pdo->prepare("SELECT * FROM products WHERE productName = ?");
$stm->bindValue(1, $prodName);
$stm->execute();
$row = $stm->fetch(PDO::FETCH_ASSOC);
$results[0] = $row["productName"];
$results[1] = $row["price"];
$results[2] = $row["quantity"];
$result=implode("','", $results);
echo $result;
Well, i would just remove %
from the search string using str_replace
//Retrieving Product Name
$prodName = str_replace('%', '', $_GET['name']);
You could also escape the percentage by putting it in brackets or using backslash:
//Retrieving Product Name
$prodName = str_replace('%', '[%]', $_GET['name']); // \% would work too instead of [%]
Since %
has special meaning, you simply need to escape it to make it used literally, using usual \
:
\% A % character; see note following the table
So you just need to str_replace()
all %
with \%
.
See: https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
There is not a single problem with retrieving a row containing % character with LIKE operator, let alone with a comparison operator used in your code.
Even with like it could only give you extra results, but never would make a problem with getting the existing result.
To claim such a problem exists, you you must prove your words by posting a Minimal Complete Verifiable example so everyone would be able to run your code and confirm the problem exists indeed.
However, in such a simple case, instead of a proof, you will just discover some simple mistake, completely irrelevant to % sign. For example, your search string gets severely encoded/escaped by some cargo cult code and naturally becomes a different string that doesn't have any matches in the database