<?php
$searchErr="";
function test_input($data) {
$data = trim($data); //whitespacess
$data = stripslashes($data); //removes backslashes n clean data from database or form
$data = htmlspecialchars($data); //converts predefined characters to html entities, encoding user input so that they cannot manipulate html codes
return $data;
}
if ($_SERVER["REQUEST_METHOD"]=="POST")
{
if(isset($_POST["searchQuery"]))
{
if(empty($_POST["searchQuery"]))
{
$searchErr="Field cannot be empty!";
}
else //no error
{
$searchData=test_input($_POST["searchQuery"]);
$searchData=preg_replace("#[^0-9a-z]#i","",$searchData);
echo $searchData;
require_once('includes/db_connect.php');
$sQuery ="SELECT * FROM food WHERE Food_Name LIKE BINARY :searchData OR Food_Description LIKE BINARY :searchData";
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare($sQuery);
$stmt->bindParam(':searchData',$searchData); //binding var to parameter
$stmt->execute(); //executing prepared statement and returning
result to obj $numResults=$stmt->rowCount();
if($numResults==0)
{
$msg="Your search did not match any of our available
foods!";
echo $msg;
}
else
{
while($row=$addResult->fetch(PDO::FETCH_ASSOC))
{
echo $row['Food_Name'];
echo "<br/>";
}
}
}
}
}
?>
<?php
I am currently working on a website. In a section, I have a search bar which i use to search for text- match from my database. However, when I am getting the results, only texts which are case-sensitive are being returned. Please can u help me? I am using Apache and phpMyAdmin
MySQL LIKE
operator is case insensitive by design, unless the related column has a case-sensitive collation.
If you want a case-sensitive seach, you can use LIKE BINARY
.
SELECT *
FROM food
WHERE
Food_Name LIKE BINARY :searchData
OR Food_Description LIKE BINARY :searchData
On the other hand, if your column has a case-sensitive collation and you want a case insensitive search, you can use lower()
to turn both the column values and the search term to lower case before comparing:
SELECT *
FROM food
WHERE
LOWER(Food_Name) LIKE LOWER(:searchData)
OR LOWER(Food_Description) LIKE LOWER(:searchData)
Please note that both approaches are not index-friendly. Bottom line, you want to use a column collation that does match your need. If you want a case-insensitive match, use a case-insensitive collation, else use a case-sensitive collation.
Important side note: your code is vulnerable to SQL injection. Do read about bind parameters and prepared statement , and consider fixing your code. I updated your query so it uses named bind variables.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.