简体   繁体   中英

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

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

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%'

You need to use LIKE , not = .

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"

WHERE name LIKE 'chuck%'

Another example where "chuck" can be anywhere.

WHERE name LIKE '%chuck%'

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.

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