php - 在不使用数组的情况下使用json从数据库中获取数据

标签 php mysql arrays json

我想使用 PHP 和 MySql 从 JSON 格式的数据库中检索对象。我只想知道如何在不必创建数组的情况下执行此操作?可以吗?

如果是这样,我可以举个例子说明如何使用这段代码草稿来完成吗?

$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;

最佳答案

$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);

输出:

 [{"name":"test","email":"test@gmail.cmom"},{"name":"test1","email":"test1@gmail.cmom"}]

关于php - 在不使用数组的情况下使用json从数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598278/

相关文章:

php - 如何在javascript中获取复选框值

php - 在 php 中替换反斜杠字符串

php - 为什么有人会使用 printf() 来处理几乎所有事情?

php - Recaptcha 不适用于 https

php - 口语变体关系数据库设计的最佳实践

mysql - FIND_IN_SET 与别名

MySQL - 无法查询现有表

arrays - 加快我的字符串文本替换代码

c - 返回指向子数组的指针

php - 将数组中的值插入表中