J. Doe
J. Doe

Reputation: 483

php echo json_encode from DB entries -> getting strange format. how to get a proper JSON

At the moment i get the following JSON:

["1Sales & Consulting","2Pyments","3Investing","4Financing","5Cross Functional"]

but i would like to have a proper JSON like:

[{"id":1, "name": "Sales & Consulting"}{"id": 2, "name": "Pyments"}{"id": 3, "Investing"}{"id": 4, "name": "Financing"}{"id": 5, "name": "Cross"}] 

The code i used to generate the first output is:

<?php
define('servername','localhost');
define('username','root');
define('password','');
define('dbname','integration');
// Create connection
$conn = new mysqli(servername, username, password, dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM capability_level1";
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $test[] = $row["id"] . $row["name"];
    }
    echo json_encode($test);
} else {
    echo json_encode("0 results");
}
$conn->close();
?>

what do i have to change? this echo is needed to pass to ajax in a second step

Upvotes: 0

Views: 46

Answers (3)

Kishen Nagaraju
Kishen Nagaraju

Reputation: 2190

Change the lines

while($row = $result->fetch_assoc()) {
    $test[] = $row["id"] . $row["name"];
}

to

while($row = $result->fetch_assoc()) {
    $test[] = array(
         'id' => $row["id"],
         'name' => $row["name"]
    );
}

Hope this helps.

Upvotes: 3

nandal
nandal

Reputation: 2634

Use the following code changes:-

<?php
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        array_push($test, $row);
    }
    echo json_encode($test);
} else {
    echo json_encode("0 results");
}
$conn->close();

?>

Upvotes: 0

Mawia HL
Mawia HL

Reputation: 3665

Try this instead:

 while($row = $result->fetch_object()) {
       array_push($test, $row);
 }
 echo json_encode($test);

Upvotes: 1

Related Questions