2017-04-04 47 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); 
});