我正在为 Android 应用程序创建 Rest 服务,并尝试从数据库中获取一些数据,但我得到的是空 JSON,实际上我什么也没得到,但我也没有收到任何错误。
这是我的数据库的结构:
这是我正在执行查询的函数:
public function getAllJokes() {
$stmt = $this->conn->prepare("SELECT id, joke, user_name, image, created_at FROM jokes ORDER BY created_at DESC");
$result = $stmt->execute();
$jokes = $stmt->get_result();
$stmt->close();
return $jokes;
}
这是 GET 请求:
$app->get('/all_jokes', function() use ($app) {
$response = array();
$db = new DbHandler();
// fetching all jokes
$result = $db->getAllJokes();
$response["error"] = false;
$response["jokes"] = array();
// looping throught result and preparing jokes array
while ($joke = $result->fetch_assoc()) {
$tmp = array();
$tmp["id"] = $joke["id"];
$tmp["joke"] = $joke["joke"];
$tmp["user_name"] = $joke["user_name"];
array_push($response["jokes"], $tmp);
}
echoResponse(200, $response);
});
所以当我尝试获取数据时,我什么也没得到。我在表中有 5 条记录。
最佳答案
尝试此代码以获得完整的解决方案。
<?php
//open connection to mysql db
$connection = mysqli_connect("hostname","username","password","db_employee") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from tbl_employee";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
关于php - 没有通过 GET 请求获取 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852043/