Andrew Quebe
Andrew Quebe

Reputation: 2293

PHP variable gets last object in database instead of all objects

First off, sorry if the title is off...it's the best thing I could think of as to what issue I'm facing.

In my database, I have a list of apps. In PHP, I'm pulling their data from their key, and encoding that data into JSON to be printed out (I'm making an API).

However, only the last app gets printed out in JSON. What I need is a JSON array with ANY apps that have the same key so I can loop through them later, and print out their data.

My code:

$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);

if ($appData->num_rows > 0){ // Check if app_key exists
    while($row = $appData->fetch_assoc()) { // While retrieving rows
        $jsonApp = json_encode(array( // Encode the row data
            "app_name" => $row['app_name'],
            "app_theme" => array(
                "primary_color" => $row['app_primary_color'],
                "primary_color_dark" => $row['app_primary_dark_color'],
                "accent_color" => $row['app_accent_color'],
            ),
            "app_navigation" => $row['app_navigation'],
            "author_info" => array(
                "author_name" => $row['app_author_name'],
                "author_bio" => $row['app_author_bio'],
                "links" => array(
                    "website" => $row['app_author_website'],
                    "googleplus" => $row['app_author_gplus'],
                    "twitter" => $row['app_author_twitter'],
                    "dribble" => $row['app_author_dribble'],
                    "behance" => $row['app_author_behance'],
                )
            ),
            "app_status" => $row['app_status']
        ), JSON_UNESCAPED_SLASHES);
    }
    // Format and print JSON data
    echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
    $jsonError = json_encode(
    array(
        array(
            "error" => array(
                "code" => "8",
                "message" => "Invalid API key specified"
            )
        )
    ), JSON_UNESCAPED_SLASHES);
    echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}

For the above, I tried echoing the JSON data in the while loop, but that (as expected) printed <pre>s for every row.

Here's the JSON output from the above code:

{
    "app_name":"Andrew's Second App",
    "app_theme":{
        "primary_color":"#FFFFFF",
        "primary_color_dark":"#E0E0E0",
        "accent_color":"#E91E63"
    },
    "app_navigation":"0",
    "author_info":{
        "author_name":"Andrew Quebe",
        "author_bio":"I'm a developer of stuff.",
        "links":{
            "website":"http://www.andrewquebe.com",
            "googleplus":"https://plus.google.com/+AndrewQuebe",
            "twitter":"https://twitter.com/andrew_quebe",
            "dribble":"None",
            "behance":"None"
        }
    },
    "app_status":"1"
}

Note: the data is perfectly formatted, but I need the data to be in an array and I'm unsure as to how to do this.

Upvotes: 0

Views: 67

Answers (4)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

The problem is, you're applying json_encode() function in each iteration of while() loop, plus you're overwriting $jsonApp in each iteration. And that's why you're getting that output.

The solution is, create an empty result array outside of while() loop. In each iteration of while() loop, push that array into the result array. And finally after coming out of the loop, apply json_encode() function on the result array and display it.

So your code should be like this:

// your code

if ($appData->num_rows > 0){ // Check if app_key exists
    $resultArr = array();
    while($row = $appData->fetch_assoc()) { // While retrieving rows
        $resultArr[] = array( // Encode the row data
            "app_name" => $row['app_name'],
            "app_theme" => array(
                "primary_color" => $row['app_primary_color'],
                "primary_color_dark" => $row['app_primary_dark_color'],
                "accent_color" => $row['app_accent_color'],
            ),
            "app_navigation" => $row['app_navigation'],
            "author_info" => array(
                "author_name" => $row['app_author_name'],
                "author_bio" => $row['app_author_bio'],
                "links" => array(
                    "website" => $row['app_author_website'],
                    "googleplus" => $row['app_author_gplus'],
                    "twitter" => $row['app_author_twitter'],
                    "dribble" => $row['app_author_dribble'],
                    "behance" => $row['app_author_behance'],
                )
            ),
            "app_status" => $row['app_status']
        );
    }
    $jsonApp = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
    // Format and print JSON data
    echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
    $jsonError = json_encode(
    array(
        array(
            "error" => array(
                "code" => "8",
                "message" => "Invalid API key specified"
            )
        )
    ), JSON_UNESCAPED_SLASHES);
    echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}

Upvotes: 1

ihilt
ihilt

Reputation: 1

I believe it's because on line 6 of your example you're assigning the output of json_encode to the $jsonApp variable. It would be easier to use an array like so.

$jsonApp[] = array(

And then use json_encode at the end.

echo "<pre>" . prettyPrint(json_encode($jsonApp)) . "</pre>";

Upvotes: 0

Omer Citak
Omer Citak

Reputation: 123

This is the format of JSON. You can not output different shapes. However, when decoding this JSON output, you can either decode objcet or array.

$object = json_decode($json);

$array = json_decode($json, true);

Upvotes: 0

Leo Wilson
Leo Wilson

Reputation: 503

In your while loop, you're constantly re-asigning values to $jsonApp. I would recommend adding the values more like this:

$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);

if ($appData->num_rows > 0){ // Check if app_key exists
    for($i=0;$row = $appData->fetch_assoc();i++) { // While retrieving rows
        $jsonApp[i] = array( // Encode the row data
            "app_name" => $row['app_name'],
            "app_theme" => array(
                "primary_color" => $row['app_primary_color'],
                "primary_color_dark" => $row['app_primary_dark_color'],
                "accent_color" => $row['app_accent_color'],
            ),
            "app_navigation" => $row['app_navigation'],
            "author_info" => array(
                "author_name" => $row['app_author_name'],
                "author_bio" => $row['app_author_bio'],
                "links" => array(
                    "website" => $row['app_author_website'],
                    "googleplus" => $row['app_author_gplus'],
                    "twitter" => $row['app_author_twitter'],
                    "dribble" => $row['app_author_dribble'],
                    "behance" => $row['app_author_behance'],
                )
            ),
            "app_status" => $row['app_status']
        );
    }
    $json = json_encode($jsonApp,JSON_UNESCAPED_SLASHES);
    // Format and print JSON data
    echo "<pre>" . prettyPrint($json) . "</pre>";
} else { // No key found, encode error
    $jsonError = json_encode(
    array(
        array(
            "error" => array(
                "code" => "8",
                "message" => "Invalid API key specified"
            )
        )
    ), JSON_UNESCAPED_SLASHES);
    echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}

This should show a JSON array, with each element in the array representing an individual app entry.

Upvotes: 1

Related Questions