如何从PHP数据库中获取数据并存储到JSON数组中?

时间:2018-06-23 09:15:59

标签: php android arrays mysqli

我一次得到一排。 (我正在使用REST API邮递员查看输出)

    {  
   "error":false,
   "uid":"5af96e2e2d1000.15095126",
   "Generalnotice":{  
      "id":1,
      "headline":"N4",
      "link":"n4.in",
      "description":"n4 desc",
      "issued_at":"",
      "updated_at":null,
      "type":"general"
   }
}

但是我想一次获取所有行。我不知道将while循环放在哪里。所有的互联网教程都带有mysql函数。

这是我的代码。 让我让您了解流程和我的需求。 我正在将字符串请求从android应用发送到php,这是我在fetchnotice.php文件(第4行)中收到的。然后我在另一个文件DB_Funtions.php中调用getGeneralNotice()函数 getGeneralNotice函数中的请求过程,其中我从数据库中获取数据并返回FetchNotice.php。如果我收到任何回复,请打印出来。.

我得到回应。但只有一排。我希望所有行都打印。 (不,我没有使用PDO)

fetchNotice.php

<?php
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    $response = array("error" => FALSE);
    if (isset($_POST['noticeType'])) {
        // receiving the post params
        $noticeType = $_POST['noticeType'];
       // getting the General Notices
       $Generalnotice = $db->getGeneralNotice($noticeType);
       if ($Generalnotice != false) {
           // General notice found
           $response["error"] = FALSE;
           $response["uid"] = $Generalnotice["unique_id"];
           $response["Generalnotice"]["id"] = $Generalnotice["id"];
           $response["Generalnotice"]["headline"] = $Generalnotice["headline"];
           $response["Generalnotice"]["link"] = $Generalnotice["link"];
           $response["Generalnotice"]["description"] = $Generalnotice["description"];
           $response["Generalnotice"]["issued_at"] = $Generalnotice["issued_at"];
           $response["Generalnotice"]["issued_at"] = $Generalnotice["role"];
           $response["Generalnotice"]["updated_at"] = $Generalnotice["updated_at"];
           $response["Generalnotice"]["type"] = $Generalnotice["type"];
           echo json_encode($response);
       }
       else {
           // user is not found with the credentials
           $response["error"] = TRUE;
           $response["error_msg"] = "Please try again!";
           echo json_encode($response);
       }
   }
   else {
       // required post params is missing
       $response["error"] = TRUE;
       $response["error_msg"] = "Required parameters are missing!";
       echo json_encode($response);
   }
?>

DB_Funtions.php

class DB_Functions {

private $conn;

function __construct() {
    require_once 'DB_Connect.php';
    // connecting to database
    $db = new Db_Connect();
    $this->conn = $db->connect();
}
    public function getGeneralNotice($noticeType) {
        $stmt = $this->conn->prepare("SELECT * FROM noticetable WHERE type = ?");
        $stmt->bind_param("s", $noticeType);
        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            return $user;
            $stmt->close();
        } else {
            return NULL;
        }
    }
}

0 个答案:

没有答案