Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:从mysql数据库获取json中的多个对象_Php_Mysql_Json - Fatal编程技术网

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

PHP:从mysql数据库获取json中的多个对象,php,mysql,json,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($locati

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

?>
嗨,我想做的是为所有具有特定位置数据的数据获取JSON对象。当我键入newjersey时,它应该为所有具有“newjersey”位置数据的数据获取对象。但是,它只打印一个数据。如何获取json格式的所有数据。ObOperations具有getPostByLocation功能,并且工作正常


谢谢大家!

如果执行
$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;
}

如果执行
$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;
}

谢谢,但是在我添加了这个之后,json为所有元素打印空值。如果您
$post
应该收到一个数组,让我们
打印出来看看它包含什么sprint\r($post);没有打印任何内容。抱歉,键入PO请更改并更新while返回代码,添加
$data
,然后添加
$data[]=$row
返回$data噢,print_r($post)正确地打印了所有包含数据的数组,但它仍然无法获得json中的对象。谢谢,但是在我添加了这个之后,json为所有元素打印空值。如果您
$post
应该收到一个数组,让我们
print_r
将它打印出来,看看它包含什么($post);没有打印任何内容。抱歉,键入PO请更改并更新while返回代码,添加
$data
,然后添加
$data[]=$row
返回$data噢,print_r($post)正确地打印所有包含数据的数组,但它仍然无法获取json中的对象。