skip to Main Content

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


  1. You can use json_encode and json_decode to convert array to JSON and vice versa.

    return json_encode($arr)
    
    Login or Signup to reply.
  2. To convert a php array into json , Use json_encode() function. And in your code, You mixed up Normal and Prepared Statements.

    public function getAllCases()
    {
        $data = array();
        $result = $this->conn->query("SELECT * FROM `mycase`");
        $num_rows = $result->num_rows;
        if ($num_rows  > 0) {                           
            while($row = $result->fetch_assoc()) {
                $data[] = $row; 
            }
         }
        return json_encode($data);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search