2
votes

my php function returns the following json object:

{"user_id":"1",
  "0":"1",

  "token":null,
  "1":null,

  "username":"bgarrett0",
  "2":"bgarrett0"}

It adding both the numeric key/values and the associative key/values. I only want the associative/values. $sql is a prepared query string, args is an array of the appropriate values for $sql.

$this->pdo (mysql db) is has attributes [PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION;PDO::ATTR_EMULATE_PREPARES, false;]

   public function query($sql, $args)
   {
    try {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($args);
        $stmt = $stmt->fetchAll();
        return json_encode($stmt);
    } catch(Exception $e) {
        $this -> error_status = $e->getMessage();
    }
  }
1

1 Answers

8
votes

Then just use the flag PDO::FETCH_ASSOC if you only want associative indices:

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
return json_encode($data);