1👍
✅
I’ll assume you want your API to return JSON data.
As you can see from your screenshot, your PHP code is currently sending a (empty) HTML response: headers: { [...] content-type: "text/html; charset=UTF-8", [...] }
. That is the default for PHP, if you intend to output JSON you will have to explicitly send the correct header.
Since your function is named fetchTodo()
I will only make it fetch the data and deal with outputting it as JSON somewhere else.
<?php
class Todo {
private $connection_string ;
public function __construct() {
// connection code. Connection is okay.
}
public function fetchTodo() {
$sql = "SELECT * FROM todo ";
$result = mysqli_query($this->connection_string, $sql);
// add this line
return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}
}
// tell whoever requested this API that we're going to send JSON data
header("Content-Type: application/json");
$todo = new Todo;
// output whatever fetchTodo() returns as JSON
echo json_encode($todo->fetchTodo());
?>
Note that this does not handle any query errors. I’ll assume your connection code sets error reporting up properly. If you don’t already have one, you might consider adding a global error handler to send a JSON response if things break, perhaps something like this.
Source:stackexchange.com