简体   繁体   中英

How to return an array of objects in Json format from MySQL using php prepared-statement

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.

您可以使用json_encodejson_decode将数组转换为JSON,反之亦然。

return json_encode($arr)

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM