Reputation: 3219
I'm creating Rest Services for Android application and trying to fetch some data from DB, but i'm getting empty JSON, actually i'm getting nothing, but also i'm getting no error there.
Here is the structure of my DB:
This is my function where i'm executing query:
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;
}
And here is the GET request:
$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);
});
So when i try to fetch data, i'm getting nothing. I have 5 records in TABLE.
Upvotes: 0
Views: 239
Reputation: 1181
Try this Code for the complete solution.
<?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);
?>
Upvotes: 1