如何使用PHP中的JSON编码mysqli结果

时间:2018-06-13 08:11:06

标签: php json

我无法使用json_encode

编码mysqli结果
<?php

$emp_id = $_GET["emp_id"];

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "overtimedtr";
$jsonData;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM employees where id ='".$emp_id."'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    if($row = mysqli_fetch_assoc($result)) {

        $empName = $row['name'];
        $empPosition = $row['position'];

    }

            $jsonData = array('empName' => "'".$empName."'",'empPosition' => "'".$empPosition."'");
} else {
    //$result["empName"] = '0 results.';
    //$result["empPosition"] = '0 results.';
}

$myjson = json_encode($jsonData,JSON_FORCE_OBJECT);
mysqli_close($conn);
echo $myjson;
?>

错误代码:

Fatal Error: Uncaught Error: Cannot use object of type mysqli_result as array in line 24.
Stack trace: #0{main} thrown in line 24.

代码从第24行开始:

        $empName = $row['name'];
        $empPosition = $row['position'];

    }
            $jsonData = array('empName' => "'".$empName."'",'empPosition' => "'".$empPosition."'");
} else {
    //$result["empName"] = '0 results.';
    //$result["empPosition"] = '0 results.';
}

$myjson = json_encode($jsonData,JSON_FORCE_OBJECT);
mysqli_close($conn);
echo $myjson;
?>

我想知道我是否遗漏了一些明显的东西。我对错误感到困惑,因为我认为下面的代码已经将我的mysqli_result对象类型转换为关联数组?

if($row = mysqli_fetch_assoc($result)) {

        $empName = $row['name'];
        $empPosition = $row['position'];

    }
$jsonData = array('empName' => "'".$empName."'",'empPosition' => "'".$empPosition."'");

我已经阅读了类似的问题,找不到任何可以解决我问题的答案,我仍然感到困惑。我对Web开发很陌生,任何见解都会非常受欢迎。提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以通过这种方式更改代码,然后再次测试

    if (low == 0 && high == 0 && signScale == 0) return decimal.Zero;