Reputation: 501
I am trying to return an array called from a public function stored in a PHP file. The returned array I need to export is in JSON format. I have the below code for calling the array (which in other cases works), but the output is just Array (the sql in phpMyAdmin returns all data)
This is the public function that should return the array, stored in a general PHP class file.
public function getIssueList() {
$sql = "select * from IssueData";
$returnValue = array();
$result = $this->conn->query($sql); // makes the connection and executes the sql
if ($result != null) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
Then I call the public function from below code:
$result = $dao->getIssueList(); //opens the connection and calls the public function
echo $result;
But the echo result I get is just the word "Array"
Above code works for other public functions, but it returns only one row and not multiple as I need in this case. Also I need to get the array as associative.
What might be wrong?
Upvotes: 0
Views: 3133
Reputation: 501
ok mostly the problem was that I was using echo instead of print_r.
Also changed below code:
if ($result != null) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
to:
if ($result != null) {
while ($returnValue[] = $result->fetch_array(MYSQLI_ASSOC));
}
Upvotes: 0
Reputation: 674
To get multiple rows rather than just one, use a while loop:
if ($result != null) {
$row = $result->fetch_array(MYSQLI_ASSOC);
while(!empy($row)){
$returnValue = array_merge($returnValue, $row);
$row = $result->fetch_array(MYSQLI_ASSOC);
}
return $returnValue;
}
Upvotes: 0
Reputation: 450
You will have to return $result as json_encode($result), also, to fill your array correctly you have to do $returnValue[] = $row;
(You might want to do a while loop to fill your array)
Upvotes: 0
Reputation: 2309
You can json_encode (http://php.net/manual/en/function.json-encode.php)
echo json_encode($result);
Upvotes: 1