Reputation: 865
I'm trying to create search in RESTful API to search for specific id and this is the code that I write:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once 'dbconfig.php';
$database = new Database();
$db = $database->getConnection();
$channel = new Channel($db);
$keywords=isset($_GET["id"]) ? $_GET["id"] : "";
$stmt = $channel->searchChannel($keywords);
$num = $stmt->rowCount();
if($num>0){
$channel_arr["channel"]=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$cat = $row['cat'];
$channel_item = array(
"id" => $id,
"title" => $title,
"cat" => $cat,
);
$stmt2 = $channel->searchChannels($cat);
array_push($channel_arr["channel"], $channel_item);
}
http_response_code(200);
echo json_encode($channel_arr);
}
else{
http_response_code(404);
echo json_encode(
array("message" => "No channels found.")
);
}
class Channel{
private $conn;
private $table_name = "esite_channels";
public $id;
public $title;
public $cat;
public function __construct($db){
$this->conn = $db;
}
function searchChannel($keywords){
$query = "SELECT
e.id, e.title, e.image, e.streamname, e.enable, e.cat, e.app
FROM
" . $this->table_name . " e
WHERE
e.id LIKE ?
";
$stmt = $this->conn->prepare($query);
$keywords=htmlspecialchars(strip_tags($keywords));
$keywords = "%{$keywords}%";
$stmt->bindParam(1, $keywords);
$stmt->execute();
return $stmt;
}
}
?>
it works fine while I search for id 20 with this link: http://127.0.0.1/api/search.php?id=20
it bring data of that id like this:
[
{
channel: [
{
id: "20",
title: "title",
cat: "Sports",
}
]
}
]
but when change the id for 22 for example: http://127.0.0.1/api/search.php?id=22
it bring me all items that contain 22 in the id like this:
[
{
channel: [
{
id: "22",
title: "BEIN SPORTS 3HD",
cat: "Sports",
},
{
id: "122",
title: "Fine Living HD",
cat: "Entertainment",
}
]
}
]
it bring 22 and 122 id while I want only the 22 and when I search for 122 I want it to bring me 122 only how do this
Upvotes: 0
Views: 1661
Reputation: 15616
Change e.id LIKE ?
to e.id = ?
in your query. And remove this line:
$keywords = "%{$keywords}%";
Because when you use LIKE
with "%keyword%"
structure, LIKE
operator searches for the records containing that value. You can also use the LIKE
operator without the wildcards (e.id LIKE '22'
), you can also achieve what you want. But the direct search is better.
$query = "SELECT
e.id, e.title, e.image, e.streamname, e.enable, e.cat, e.app
FROM
" . $this->table_name . " e
WHERE
e.id = ?
";
$stmt = $this->conn->prepare($query);
$keywords=htmlspecialchars(strip_tags($keywords));
$stmt->bindParam(1, $keywords);
Upvotes: 3