Reputation: 3560
I can not search the value from Database putting the key word using PHP and MySQL. Here is my code:
$searchKey=$_GET['searchKey'];
$special_id=$_GET['special_id'];
$city_id=$_GET['city_id'];
$day_id=$_GET['day_id'];
$keyword = '%'.$searchKey.'%';
$data=array();
$sql =mysqli_query($connect,"SELECT * FROM db_restaurant_basic WHERE rest_name LIKE '".$keyword."' and special='".$special_id."' and city='".$city_id."' and status=1 GROUP BY member_id ORDER BY member_id DESC ");
if(mysqli_num_rows($sql) > 0){
while($row=mysqli_fetch_array($sql)){
$data[]=array("restaurant_name"=>$row['rest_name']);
}
}
$result=array("data"=>$data);
echo json_encode($result);
When i am calling the following URL to get the result.
http://localhost/spesh/mobileapi/categoryproduct.php?item=2&acn=5&special_id=1&city_id=1&day_id=4&searchKey=on
Its giving me the following result.
{"data"[{
"restaurant_name":"Sonoma on 9th"
},{
"restaurant_name":"Jamesons Irish Pub 17th Ave. SW"
},{
"restaurant_name":"Jamesons Irish Pub Brentwood NW"
},{
"restaurant_name":"National on 17th"
}
]
}
My problem is I need to search the Restaurant name
which contains the keyword on
but I am getting some other Restaurant name
which doesn't contain keyword on
. I need when user will search the restaurant name using keyword on
it should give the restaurant name which contains that word on
only not other restaurant name.
Upvotes: 1
Views: 86
Reputation: 1203
Instead of using direct substitution values, you could use below methods to avoid sql injection.
You basically have two options to achieve this:
Refer docs
For example, using MySQLi (for MySQL):
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Please refer How can I prevent SQL-injection in PHP?
Upvotes: 0
Reputation: 69440
add blanks around the keyword:
$keyword = '% '.$searchKey.' %';
By the way: Learn abut prepared statements to prevent SQL-injection.
Upvotes: 2
Reputation: 190
you are using keyword "like" in your query which search "on" everywhere in restaurant name.
you should use spaces to make it specific
$keyword = '% '.$searchKey.' %';
check the spaces after first % sign and before the second one
Upvotes: 3