简体   繁体   English

如何在PHP中使用mysql数据库过滤Rest api响应

[英]How to filter Rest api response using mysql database in PHP

I am currently working on a JSON Api project using php and mysql database I have been able to create a post and get function successfully i am trying to implement a filter feature but only able to retrieve one result even when more than one of the result has similar names Example my database contains "chuck", and "chuck Morris" when i search for "chuck" i want to be able to retrieve both names but am only getting the result with the exact name ie "chuck" just one result Here is my code for the search function我目前正在使用 php 和 mysql 数据库处理 JSON Api 项目我已经能够成功创建帖子并获取函数我正在尝试实现过滤器功能但只能检索一个结果即使有多个结果相似名称示例 我的数据库包含“chuck”和“chuck Morris”,当我搜索“chuck”时,我希望能够检索这两个名称,但我只得到具有确切名称的结果,即“chuck”只有一个结果我的搜索功能代码

public function read_singleName() {
    $sql_query = "SELECT * FROM ".$this->table_name . " WHERE name = ?";
    $obj = $this->conn->prepare($sql_query);
    $obj->bind_param("s", $this->name);
    $obj->execute();
    $data = $obj->get_result();
    return $data->fetch_assoc();
}

Here is the code to display the results这是显示结果的代码

if($_SERVER['REQUEST_METHOD'] === "GET"){

  $artist_name = isset($_GET['name']) ? strval($_GET['name']) : "";

  if(!empty($some_name)){

    $some->name = $some_name;
    $some_data = $some->read_singleName();

    if(!empty($some_data)){
      http_response_code(200);
      echo json_encode(array(
          "status" => 1,
          "data" => $some_data
      ));
    } else{
      http_response_code(500);
      echo json_encode(array(
        "status" => 0,
        "message" => "Name Not Found"
      ));
    }   
    }   

} else{
    http_response_code(503);
    echo "Access Denied";
    echo json_encode(array(
        "status" => 000,
        "message" => "Failed"
    ));
}

No sure what $this->conn is but I think you should call fetch_assoc() in a while loop until there are no more records不确定$this->conn是什么,但我认为您应该在 while 循环中调用fetch_assoc()直到没有更多记录

while($record = $data->fetch_assoc()){
    // do something with $record
}

Also the query should be like this: SELECT * FROM ".$this->table_name . " WHERE name LIKE '%chuck%'查询也应该是这样的: SELECT * FROM ".$this->table_name . " WHERE name LIKE '%chuck%'

You need to use LIKE , not = .您需要使用LIKE ,而不是=

When you do this:当你这样做时:

    $sql_query = "SELECT * FROM ".$this->table_name . " WHERE name = ?";

You will only get exact matches.你只会得到完全匹配。

What you need is this:你需要的是这个:

    $sql_query = "SELECT * FROM ".$this->table_name . " WHERE name LIKE ?";

And then use % characters as wild cards.然后使用%字符作为通配符。

This will find everything that begins with "chuck"这将找到以“chuck”开头的所有内容

WHERE name LIKE 'chuck%'

Another example where "chuck" can be anywhere. “chuck”可以在任何地方的另一个例子。

WHERE name LIKE '%chuck%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM