php - 没有通过 GET 请求获取 JSON 响应

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

所以当我尝试获取数据时,我什么也没得到。我在表中有 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/

相关文章:

php - 具有社交网站集成的最佳 codeigniter 2.1 身份验证库

php - 我将如何阻止访问没有 url 的 PHP 页面?

php - 如何将多维与特定值合并

Android 如何让 Gallery 自动滚动到第一项?

android - 在 Windows 8 64 位上安装 Nexus 4(带 KitKat)的 USB 驱动程序 - "no compatible software driver"

MySQL 和检查约束

phpunit + symfony 错误处理程序已更改

android - 获取数据库行中的所有数据以显示 Android SQLite

mysql - 如何检查表中单行SQL中的任何值是否为Null

php - 使用 Maat、Excel 和 Laravel 的导入函数问题