簡體   English   中英

json_encode正在截斷從mysql數據庫讀取的對象數據

[英]json_encode is truncating the object data read from mysql database

我正在使用MySql作為數據庫引擎在PHP 5.6.8中開發Web應用程序。

在驗證用戶是否具有適當憑據的方法中,我正在調用數據庫並檢索用戶對象。 功能代碼為:

function getBoosterDetails($patientId){
       $dbConnection = new Database();

       $sql = "SELECT * from users where id = :patientId";
       try {
           $db = $dbConnection->getConnection();
           $stmt = $db->prepare($sql);
           $stmt->bindParam("patientId", $patientId);
           $stmt->execute();
           $userDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
           $db = null;
           $_SESSION['userDetails'] = $userDetails;

           echo '{"user": ' . json_encode($userDetails) . '}';


       } catch(PDOException $e) {
           echo '{"error":{"text":'. $e->getMessage() .'}}'; 
       } catch(Exception $e1) {
           echo '{"error11":{"text11":'. $e1->getMessage() .'}}'; 
       } }

對於任何有效的輸入,我一直得到對象無效的錯誤。 我嘗試在Advanced Rest Client Chrome插件中檢查userDetails對象。 我觀察到的是,雖然對象的var轉儲具有整個對象數據,但json_encode的回顯卻被截斷,如下圖所示。

![在此處輸入圖片描述] [1]

我已經用XAMPP設置了Apache&MySql服務器(並且也曾在MAMP上嘗試過,並得到了相同的結果。)

// this is the var_dump
    stdClass object
(
    [username]  => pavan
    [rolename]  => Patient
    [userid]  => 5
)

//this is the json_encode echo output
{"user": [{"username":"pavan", "rolename":"Patient", "userid":

內容經過json編碼時會被截斷。請您幫我解決一下。

不要包裝json-in-json。 那是錯誤的。

用您的宿主語言(例如php)構建一個SINGLE數據結構,然后對ENTIRE結構進行編碼:

$data = array(
   'user' => $userDetails
);
$json = json_encode($data);

您的代碼在語法上產生了ILLEGAL json ...

   echo '{"user":' . json_encode($userDetails) . '}}';**
         ^--open #1                               ^--close #1
                                                   ^--close #2

#2大括號關閉是什么? 如果您完成了單結構編碼,那將是不可能的。

您可以嘗試下面的代碼,而不是現有的代碼嗎?

我們只是將PDO :: FETCH_OBJ更改為PDO :: FETCH_ASSOC,它返回數組格式。

更新的代碼:

函數getBoosterDetails($ patientId){$ dbConnection = new Database();

   $sql = "SELECT * from users where id = :patientId";
   try {
       $db = $dbConnection->getConnection();
       $stmt = $db->prepare($sql);
       $stmt->bindParam("patientId", $patientId);
       $stmt->execute();
       $userDetails = $stmt->fetchAll(PDO::FETCH_ASSOC);
       $db = null;
       $_SESSION['userDetails'] = $userDetails;

       echo '{"user": ' . json_encode($userDetails) . '}';


   } catch(PDOException $e) {
       echo '{"error":{"text":'. $e->getMessage() .'}}'; 
   } catch(Exception $e1) {
       echo '{"error11":{"text11":'. $e1->getMessage() .'}}'; 
   } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM