2017-04-04 95 views
1

我試圖在PHP Slim framework中執行一個獲取請求。但是我的MYSQL數據庫中有一個BLOB變量。其中包含stringsarray。如何檢索BLOB變量並將其轉換回stringsarray帶有BLOB變量的Slim GET請求

這裏是我取的方法

// fetch all apps 
$app->get('/apps', function ($request, $response, $args) { 
    $sth = $this->db->prepare("SELECT * FROM app ORDER BY updated_at"); 
    $sth->execute(); 
    $apps = $sth->fetchAll(); 
    return $this->response->withJson($apps); 
}); 

這裏$apps有一個名爲locale變量,它是BLOB。我想退回$appsarraystrings

+0

如何被存儲到BLOB字符串數組?什麼是當前代碼的JSON輸出? –

回答

0

我這樣做是錯誤的。我試圖將Array對象直接保存到BLOB中。由於在檢索它,我得到一個字符串「數組」,而不是我的Array數據。

現在,我將array編碼爲JSON String,然後將其保存到BLOB變量中。我正在將string解碼回JSON

這是我如何保存應用程序

// add new app 
$app->post('/saveApp', function ($request, $response) { 
    $input = $request->getParsedBody(); 
    $input['locale'] = json_encode($input['locale']); 

    $sql = "INSERT INTO app (id,name,locale) VALUES (:id,:name,:locale)"; 
    $sth = $this->db->prepare($sql); 
    $sth->bindParam("id", $input['id']); 
    $sth->bindParam("name", $input['name']); 
    $sth->bindParam("locale", $input['locale']); 
    $sth->execute(); 
    $input['id'] = $this->db->lastInsertId(); 
    return $this->response->withJson($input); 
}); 

這是我如何獲取應用

// fetch all apps 
$app->get('/apps', function ($request, $response, $args) { 
    $sth = $this->db->prepare("SELECT * FROM app ORDER BY updated_at"); 
    $sth->execute(); 
    $apps = $sth->fetchAll(); 
     $result = array(); 
     foreach ($apps as $app) { 
      $app['locale'] = json_decode($app['locale']); 
      array_push($result, $app); 
     } 
    return $this->response->withJson($result); 
});