2017-10-21 36 views
1

get_post.phpPHP:從MySQL數據庫得到JSON多個目標

<?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對象有一定的位置數據。當我鍵入新澤西州時,它應該獲取具有「新澤西州」位置數據的所有數據的對象。但是,它只打印一個數據。我如何獲取json格式的所有數據? ObOperations具有getPostByLocation函數,並且它可以正常工作。

謝謝!

回答

0

如果你做你只是得到第一行,你應該使用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; 
} 
+0

謝謝你,但我加了這個之後,JSON打印空所有元素 – Eric

+0

然後你'$ POST'應該接受一個數組,讓我們'print_r'出來,看看它包含 –

+0

的print_r($崗位);不打印任何東西。 – Eric