I want to create a search bar to query my MySql Db.
<?php
$query = $_POST['search_name'];
$min_length = 3;
if(strlen($query) >= $min_length){
$query = mysqli_real_escape_string($connection,$query);
$raw_results = mysqli_query($connection, "SELECT * FROM `companies`
WHERE (`name` LIKE '%$query%')");
if(mysqli_fetch_row($raw_results) > 0){
while($results = mysqli_fetch_row($raw_results)){
echo "<p>".$results[0]." ".$results[1]."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
Now, If I type in the bar gaio , I don't get the result Gaiotto Automation
. Surprisingly if I type the query directly in the SQL terminal
SELECT * FROM `companies` WHERE (`name` LIKE '%gaio%')
then the result is Gaiotto Automation
, that is what I want. If I type in the search bar autom
then I get Gaiotto Automation
amongst the results.
Be careful using php var in your sql code you are at risk for sqlinjection
for avoid this you should check for your db driver for binding param
Anyway You should build the query strung patter in a proper way eg: uisng concat
$raw_results = mysqli_query($connection, "SELECT * FROM `companies`
WHERE (`name` LIKE concat('%', '$query', '%') )");
You have to use mysqli_num_rows
instead of mysqli_fetch_row
in if condition
as it already extracted the results in if condition so it won't work next time.
<?php
$query = $_POST['search_name'];
$min_length = 3;
if(strlen($query) >= $min_length){
$query = mysqli_real_escape_string($connection,$query);
$raw_results = mysqli_query($connection, "SELECT * FROM `companies` WHERE (`name` LIKE '%$query%')");
if(mysqli_num_rows($raw_results) > 0){
while($results = mysqli_fetch_row($raw_results)){
echo "<p>".$results[0]." ".$results[1]."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
I suspect that your parameter is not trimmed, but in any case I suggest that you use prepared statements
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You know that your sql syntax works directly so you can debug by echoing the sql statement on the post page.
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.