Data returned in an array is duplicated

3

I'm running a SELECT in the database through a function and returning the result as a multidimensional array, where each primary index refers to a record, and the secondary indexes are the bank fields with the values.

Below is the function return assembly:

$resultado = $this->conn->query($sql);
if ($resultado->rowCount() > 0) {
   foreach($resultado as $chave => $valor){
      $retorno[$chave] = $valor;
   }
   return $retorno;
} else {
   return false;
}

When I get the return and execute a var_dump() , the result looks like this:

array (size=3)
  0 => 
    array (size=4)
      'usu_id' => string '1' (length=1)
      0 => string '1' (length=1)
      'usu_nome' => string 'Administrador' (length=13)
      1 => string 'Administrador' (length=13)

The second dimension of the array is creating two indexes for the return: "0" and "usu_id", as well as "1" and "usu_name".

Is that correct? Does PHP act anyway or is there an error in the way I'm mounting the return array?

    
asked by anonymous 08.03.2018 / 14:07

1 answer

5

By default the query return of the PDO is the PDO :: FETCH_BOTH that returns the duplicate data being an index with the name of the field and another numerical index.

You can define the data format in three ways:

In the constructor that affects all queries made by this connection.

$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$pdo = new PDO('.....', $options);

In the query() method only the current query is affected.

$result = $pdo->query('select ....', PDO::FETCH_ASSOC);

And lastly on extraction in method fetch() / fetchAll() where format is passed as argument.

 $result = $pdo->query('select ....');
 $info = $result->fetchAll(PDO::FETCH_ASSOC);
 foreach($info as $item){
    echo $item['chave'] .'<br>';
 }

As only returns the data without any manipulation can give the return direct in query() or fetch() if you want to add treatment to errors.

$resultado = $this->conn->query($sql);
if ($resultado->rowCount() > 0) {
    return $resultado->fetchAll(PDO::FETCH_ASSOC);
} else {
   return $this->conn->errorInfo();
}
    
08.03.2018 / 14:28