MMelvin0581
MMelvin0581

Reputation: 503

Funky output in json_encode

I'm getting some weird output when I json_encode the response from my MySQL database. I'm VERY new to PHP and only working with it for school, any help is appreciated.

Here is the code:

<?php
require_once('./database.php');

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

if (isset($_GET['format'])) {
    $format = filter_var($_GET['format']);
}

if (isset($_GET['action'])) {
    $action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
    $tableName = "sk_$action";
}

$query = "SELECT * FROM $tableName";

if (isset($_GET['course'])) {
    $course = filter_input(INPUT_GET, 'course');
    $query .= " WHERE courseID = :course_id";
}

$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();

$response = $statement->fetchAll();

$statement->closeCursor();

echo json_encode($response);

Here is the response:

enter image description here

I don't know where the 0's and 1s are coming from, nor how to get rid of them. Can someone please point me in the right direction?

Ok, so I added this to the code and now the application crashes.

$response = $statement->fetchAll(PDO::FETCH_ASSOC);

$statement->closeCursor();

if ($format == 'json') {
    echo json_encode($response);
}
if ($format == 'xml') {
    $xml = new SimpleXMLElement($response[0]);
    array_walk_recursive($response, array($xml, 'addChild'));
    print $xml->asXML();
}

The JSON part works correctly, but when I have format=xml, the page doesn't load. Got anymore of those good hints guy?

Upvotes: 5

Views: 60

Answers (2)

Marty
Marty

Reputation: 39456

Those are due to the default fetch_style of PDOStatement::fetchAll(), which returns both 0-indexed and named columns for your rows.

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

You can use PDO::FETCH_ASSOC or PDO::FETCH_OBJ to capture just the column names (the former producing an associative array keyed with the column names and the latter producing an anonymous object whose properties are the column names):

$response = $statement->fetchAll(PDO::FETCH_ASSOC);

Upvotes: 7

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

Change your database fetch_style to an associative one:

If you are using PDO, check out PDO::FETCH_ASSOC

Upvotes: 2

Related Questions