Result from MySQL to JSON



  • There's a code like this:

    <?php
        mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
        mysql_select_db('my_base2') or die('Не могу выбрать базу данных');
        $query = "SELECT * FROM table1 WHERE ID<=2";
        $result = mysql_query($query) or die('Query failed: ' . mysql_error());
        while ($row = mysql_fetch_object($result)) {
            $rows[] = array($row);
        }
    
    echo json_encode($rows)
    

    ?>

    At the exit, the result is:

    [
    [{
    "ID":"1",
    "telephone_num":"89266677121",
    "date_added":"12.07.2016",
    "nick_name":"Stas",
    "firma":"Xtrun",
    "comment":"Voohoo!",
    "like":"0"
    }],
    [{
    "ID":"2",
    "telephone_num":"89263324311",
    "date_added":"12.09.2016",
    "nick_name":"Vovchik",
    "firma":"\u041e\u041e\u041e \u041c\u0438\u0440 \u0412\u0430\u043c",
    "comment":"\u0413\u0430\u0432\u043d\u043e",
    "like":"1"
    }]
    ]

    It appears that there are other positions within one body in separate areas. How to create such a structure Json:

    {
    "orderID":12345,"contents":[
    {
    "ID":1,"telephone_num":"453453","nick_name":"Kolya"
    },
    {
    "ID":2,"telephone_num":"2342525","nick_name":"Vova"
    }
    ]
    }



  • Do whatever you need and get it back.

    $response = [
        'orderID'=>12345,
        'contents'=>[]
    ];
    while ($row = mysql_fetch_object($result)) {
        $response['contents'][] = [
            'ID'=>$row->ID,
            'telephone_num'=>$row->telephone_num,
            'nick_name'=>$row->nick_name
    
    ];
    

    }
    echo json_encode($response);




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2