Php函数,它将SQL查询作为参数并返回JSON字符串

时间:2018-01-24 15:03:42

标签: php json

这是我的功能到目前为止,如何将项目转换为json并打印出来?

$query = 'SELECT * FROM department';
function dataGenerator($query) {
$conn = oci_new_connect('u','p','h') or die ("dbdn");
$stid = oci_parse($conn, $query);
$r = oci_execute($stid);

while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    foreach ($row as $item) {
        print ($item); }
}
}
dataGenerator("SELECT * FROM department");

2 个答案:

答案 0 :(得分:1)

制作项目数组,然后使用json_encode生成json为字符串

$items = [];
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    foreach ($row as $item) {
        $items[] = $item;
    }
}

$json = json_encode(array("items" => $items))

答案 1 :(得分:1)

使用json_encode,您的函数应该返回

function dataGenerator($query) {
$conn = oci_new_connect('u','p','h') or die ("dbdn");
$stid = oci_parse($conn, $query);
$r = oci_execute($stid);

while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {

          $result[] = $row;
}
return json_encode($result);
}