简体   繁体   中英

Slim $app->render issues for a JSON API

This is a fairly simple Slim $app->render question, but I'm using an SQL query to return the total number of columns in a table via $result , and the data stored in it looks like this: [{"total":"12345"}]

I want to push that out to a JSON API like so:

$app->get('/api/total/', function() use ($app) {
  $query = "select count(*) AS total FROM sometable";
  $data = $app->db->query($query);
  $result = $data->fetchAll(PDO::FETCH_OBJ);
  $app->render(
    200, json_encode(array(
      'total' => $result['total']
    ))
  );
});

How do I make Slim's $app->render produce {total:12345} ?

Doing 'total' => $result['total'] throws errors such as:

NOTICE: Undefined index: total

It is because fetchAll returns array of results. You could use fetch() instead. It would be also nice to check if fetch does not fail. However in this particular case if sometable exists it should not. Also you use fetch_obj and you try to access it as an array which is wrong. Either use FETCH_ASSOC or use FETCH_OBJ with proper object access.

$app->get('/api/total/', function() use ($app) {
  $query = "select count(*) AS total FROM sometable";
  $data = $app->db->query($query);
  $result = $data->fetch(PDO::FETCH_OBJ);
  if($result !== false) {
    $app->render(
     200, json_encode(array(
      'total' => $result->total
      ))
   );
  } else {
     $app->render(
     404, json_encode(array(
      'error' => 'Not Found'
      ))
   );
  }
 });

Also remember it is good to set content type

$app->response->headers->set('Content-Type', 'application/json');

If you need to know how fetching works check: http://php.net/manual/en/pdostatement.fetch.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM