0

This is my function so far, how do I convert the item to json and print it?

$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");
4
  • What have you tried? Nothing in your function suggests you're attempting to create a JSON string. For example, have you looked up json_encode? Commented Jan 24, 2018 at 15:05
  • print (json_encode($item)); Commented Jan 24, 2018 at 15:06
  • @J.Litvak that wont work well inside that loop ;) Commented Jan 24, 2018 at 15:06
  • 1
    Just from a coding point of view - make the database connection outside the function (better to make 1 connection per page) and pass in as a parameter. Commented Jan 24, 2018 at 15:20

2 Answers 2

1

use json_encode and your function should have a return

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

How do i log this json data onto console as a object
console.log('<?php echo $your_json ?>')
1

make array of items and then use json_encode to generate the json as string

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.