Search code examples
phparraysjsondust.js

how to solve anonymous array?


this is my php sql code

//fetch table rows from mysql db
$sql = "select * from tbl_sample";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));


//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}

$info = json_encode($emparray);
echo $info;

//close the db connection
mysqli_close($connection);
?>

when I run this code i'm getting an an anonymous json array like this.

[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]

is there a way to give this array a name because without a named array I don't know how to use this json data for dust.js template. If not suggest me how I can use this data for my templating. thank you.


Solution

  • //fetch table rows from mysql db
    $sql = "select * from tbl_sample";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
    
    
    //create an array
    $emparray = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    $mydata['my_data'] = $emparray; 
    
    $info = json_encode($mydata);
    echo $info;
    
    //close the db connection
    mysqli_close($connection);
    

    Try this. Your data will look like this

    {"my_data":[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]}