没有通过GET请求获得JSON响应

时间:2016-04-25 22:13:22

标签: php android mysql json

我正在为Android应用程序创建Rest服务并尝试从数据库中获取一些数据,但是我得到了空的JSON,实际上我什么也没得到,但我也没有收到任何错误。

这是我的数据库的结构:

DB

这是我正在执行查询的函数:

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);
});

因此,当我尝试获取数据时,我什么都没得到。我在TABLE中有5条记录。

1 个答案:

答案 0 :(得分:1)

尝试使用此代码获取完整的解决方案。

<?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);
?>