duanhe4155 2017-10-06 04:27
浏览 93
已采纳

使用json从数据库中获取数据而不使用数组

I would like to retrieve objects from the database in JSON using PHP and MySql. I would just like to know how to do this without having to create an array? Can it be done?

If so, can I get an example of how that can be done with this draft piece of code?

$sql = "SELECT Email  , FirstName, LastName,Contact FROM tblUser where UserID=sessionID";
$result = mysqli_query($conn,$sql);

while($row = mysqli_fetch_array ($result)) {
    $arr = array(
        $row["Email"],
        $row["FirstName"],
        $row["LastName"],
        $row["Contact"]
    );

    array_push($json, $arr);
}

$jsonstring = json_encode($json);
echo $jsonstring;
  • 写回答

1条回答 默认 最新

  • dpoh61610 2017-10-10 04:26
    关注
    $sql = "select name,email from contact";
    
    $res = mysqli_query($conn,$sql) or die(mysqli_error($conn));
    $num = mysqli_num_rows($res);
    
    $json = array();
    if($num > 0)
    {
        while ($obj=mysqli_fetch_object($res))
        {
            $json[] = $obj;
        }
    }
    echo json_encode($json);
    

    output:

     [{"name":"test","email":"test@gmail.cmom"},{"name":"test1","email":"test1@gmail.cmom"}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog