Mike Ross
Mike Ross

Reputation: 2972

JSON response dump first record of the array

I have a webservice name geteventsPost.php which is basic code to return data in JSON format

I tried to debug in browser tools, from which it seems like in that variable event there is always one record short. Very first record of the query gets dumped Here is my JSON webservice code I tried to see the response in web browser it look like it returns one record short.

<?php
include 'dbconnection.php';


/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

if(isset ($_GET['id'])) {
// get all products from products table
try {
    $sql = "SELECT * FROM event where organiser_id =".$_GET['id'];
    $result = $pdo->query($sql);
}
catch (PDOException $e)
{
    echo 'Error fetching data: ' . $e->getMessage();
    exit();
}

}


// check for empty result
if ($result->fetch() > 0) {
// looping through all results
// master menu node
$response["event"] = array();

while ($row = $result->fetch()) {
    // temp user array
    $event= array();
    $event["id"] = $row["id"];
    $event["title"] = $row["title"];
    $event["location"] = $row["location"];
    $event["start_date"] = $row["start_date"];


    // push single menu into final response array
    array_push($response["event"], $event);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No event found";

// echo no users JSON
echo json_encode($response);
}
?>

So i just want to know that what am i doing wrong? I am guessing its in the script code some where i am handling the response wrong.

Let me know thank you

Upvotes: 1

Views: 117

Answers (1)

Elias Nicolas
Elias Nicolas

Reputation: 740

Check this out:

if ($result->rowCount() > 0) {
$response = array();
    while ($row = $result->fetch()) {
        $response["event"][] = $row; 
    }
$response["success"] = 1;
echo json_encode($response);
}

I don't know more about how you are handling the json but you should add that if this doesn't answer your question.

Upvotes: 1

Related Questions