这是我第一次创建restAPI。 API 应该只能处理一个请求,该请求返回表中的所有数据。我完成了本教程http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/了解如何在 PHP 中创建 Rest API。
我遇到的问题是 API 调用返回空响应,并且我无法找出错误所在。这里的代码:
索引.php
<?php
/**
* Created by IntelliJ IDEA.
* User: Jakob Abfalter
* Date: 19.08.14
* Time: 14:17
*/
require_once '../include/DbHandler.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
/**
* Echoing json response to client
* @param String $status_code Http response code
* @param Int $response Json response
*/
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
/**
* Listing all foods
* method GET
* url /foods
*/
$app->get('/foods', function() {
$response = array();
$db = new DbHandler();
// fetching all foods
$result = $db->getAllFoods();
$response["error"] = false;
$response["foods"] = array();
// looping through result and preparing tasks array
while ($food = $result->fetch_assoc()) {
$tmp = array();
$tmp["id"] = $food["id"];
$tmp["name"] = $food["name"];
$tmp["img"] = $food["img"];
$tmp["description"] = $food["description"];
array_push($response["foods"], $tmp);
}
echoRespnse(200, $response);
});
$app->run();
?>
DbHandler.php
<?php
/**
* Created by IntelliJ IDEA.
* User: Jakob Abfalter
* Date: 19.08.14
* Time: 14:28
*/
class DbHandler
{
private $conn;
function __construct()
{
require_once dirname(__FILE__) . './DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
/**
* Fetching all foods from database
*/
public function getAllFoods() {
$stmt = $this->conn->prepare("SELECT * FROM foods");
$stmt->execute();
$foods = $stmt->get_result();
$stmt->close();
return $foods;
}
}
DbConnect.php:
<?php
/**
* Created by IntelliJ IDEA.
* User: Jakob Abfalter
* Date: 19.08.14
* Time: 14:27
*/
class DbConnect {
private $conn;
function __construct() {
}
/**
* Establishing database connection
* @return database connection handler
*/
function connect() {
include_once dirname(__FILE__) . './Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
?>
.htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
当我在 chrome 高级 Rest 客户端中测试请求时,它说:
我还尝试在创建数组的函数中添加一些回显,并在 Rspnse 函数中添加一些回显,但两者都没有显示
最佳答案
哦,实际上我可能错了。
这看起来即使不是问题,也是一个问题。
您的方法getAllFoods()
关闭stmt句柄$stmt->close();
然后,您将句柄传递回调用代码并尝试使用它处理所有结果。
在处理完句柄的结果之前,不应关闭该句柄。
关于PHP Rest API readAll 返回空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25384619/