I’m trying to write a function in php that will allow me to return an array of objects (in my case the objects are the rows in my database(MySQL) from phpMyAdmin) into a Json format.
Here is my function:
public function getAllCases()
{
$stmt = $this->conn->prepare("SELECT * FROM mycase ");
$stmt->execute();
$arr = []
$result = $stmt->get_result();
while($row = $result->fetch_object()) {
$arr[] = $row;
}
return $arr;
}
I couldn’t find anything else online and this function is not working.
For example if my table has 4 rows, I want to be able to get 4 objects and each one of those 4 objects should represent a row from the table and it’s columns.
Any help would be appreciated.
2
Answers
You can use json_encode and json_decode to convert array to JSON and vice versa.
To convert a php array into json , Use json_encode() function. And in your code, You mixed up Normal and Prepared Statements.