PHP:从mysql数据库中获取json中的多个对象

时间:2017-10-21 01:52:09

标签: php mysql json

get_post.php

<?php
require_once 'database_config/DbOperations.php';

$response = array();

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $location = $_POST['location'];

    $db = new DbOperations();

    $post = $db->getPostByLocation($location);

    $response['id'] = $post['id'];
    $response['name'] = $post['name'];
    $response['gender'] = $post['gender'];
    $response['dob_year'] = $post['dob_year'];
}

echo json_encode($response);

?>

ObOperations.php

public function getPostByLocation($location)
    {
        $stmt = $this->con->prepare("select * from table_post where location = ?");
        $stmt->bind_param("s", $location);
        $stmt->execute();

        return $stmt->get_result()->fetch_array();
    }

嗨,我想要做的是获取具有特定位置数据的所有数据的JSON对象。当我键入New Jersey时,它应该为具有“New Jersey”位置数据的所有数据获取对象。但是,它只打印一个数据。如何以json格式获取所有数据。 ObOperations有getPostByLocation函数,它可以正常工作。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果你做$stmt->get_result()->fetch_array();你刚刚获得第一行,你应该使用while循环来反转所有行,例如

<?php
public function getPostByLocation($location)
{
    $stmt = $this->con->prepare("select * from table_post where location = ?");
    $stmt->bind_param("s", $location);
    $stmt->execute();

    $data = array();
    $result = $stmt->get_result();
    while($row = $result->fetch_array())
    {
        $data[] = $row;
    }
    return $data;
}