简体   繁体   中英

Mysql getting json from nested queries

I had two tables whch are visitormaster and visitor comment. Visitor master has unique visitorid and comment bt that visitor stores in visitorcomment using visitorid as foreign key there. I want to get data in following format:

[
    {
        "visitorid":1,
        "visitorname":"ABC",
        "comment":
                {
                    "commentid":2;
                    "comment":"XYZ"
                }
    }
    {
        "visitorid":2,
        "visitorname":"LMN",
        "comment":
                {
                    "commentid":4;
                    "comment":"MNO"
                }
    }

]

$sql = mysql_query("SELECT * FROM visitormaster");
if(mysql_num_rows($sql) > 0)
{
    $result = array();
    while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
    {
        $result[] = $rlt[];
        $vid=$rlt["visitorid"];
        $sql1 = mysql_query("SELECT * FROM visitorcomment WHERE visitor_id = "."'$vid'");
        while($rltcomment = mysql_fetch_array($sql1,MYSQL_ASSOC))
        {
            $commentresult[] = $rltcomment[];
        }
        $newresult=array($result,"comment"=>$rltcomment[0]);
    }
    $array=array("result_data"=>$newresult);
    $this->response($this->json($array), 200);
}

But there is no output.

quote missing in SQL statement mysql_query("SELECT * FROM visitormaster);

to see errors use ini_set("Display_errors","On"); to turn error reporting on. this will give errors.

$sql = mysql_query("SELECT * FROM visitormaster);缺少双引号$sql = mysql_query("SELECT * FROM visitormaster);并且$newresult = array($result, "comment" => $rltcomment[0])也缺少半逗号。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM