Error building a JSON in PHP

2

I'm trying to build a JSOn from PHP, but when I put two conditions it does not generate the data.

That is, I only need to bring the data of SARA , but when I put them in id_ppl and level at the same time, I get nothing. I do not really know what I'm doing wrong.

I tried it by postman changing the variables, bring it only by id, or by user and it works, but when I put the previous two I do not get anything.

Table

id |  usuario  | password | token | id_ppl | nivel | multi  |
-------------------------------------------------------------
1  | Juana     | *****    |       | 1      | 1     | on     |
-------------------------------------------------------------
2  | Sara      | *****    |       | 1      | 2     | on     |
-------------------------------------------------------------

PHP Script

require 'conn.php';

    if (mysqli_connect_errno()) {
        echo "Gagal terhubung MySQL: " . mysqli_connect_error();
    }

    $id = $_GET["id"]; 
    $nivel = $_GET["nivel"]; 
    $query = mysqli_query($connect, "SELECT id, nivel, multi FROM escolar_users WHERE id_ppl = '$id' AND nivel='$nivel'");

    $json = '{"loadUser": [';

    while ($row = mysqli_fetch_array($query)){


        $char ='"';

        $json .= 
        '{
            "id":"'.str_replace($char,''',strip_tags($row['id'])).'",
            "nivel":"'.str_replace($char,''',strip_tags($row['nivel'])).'", 
            "multi":"'.str_replace($char,''',strip_tags($row['multi'])).'"
        },';
    }

    // buat menghilangkan koma diakhir array
    $json = substr($json,0,strlen($json)-1);

    $json .= ']}';

    // print json
    echo $json;

    mysqli_close($connect);

URL method GET

load.php?id_ppl=1&nivel=2
    
asked by Franck 02.08.2018 в 18:05
source

1 answer

4

You are doing the json the hard way, there is a pre-established php function called json_encode .

The query tries to make it to itself, without the single quotes:

$query = "SELECT id, nivel, multi FROM escolar_users WHERE id_ppl = $id AND nivel = $nivel";

Examples of json_encode:

$test = array(
    "success" => true,
    "msg" => $message,
    "id" => $value
)

echo json_encode($test);

#output
{"success":true,"msg":"","id":100}

Plus:

  • Do not forget to use header('Content-Type: application/json'); in the upper part of your function so that the website / page is displayed as json.

  • there are extensions in google chrome to show nice the json, just look for them

answered by 02.08.2018 в 18:13