How do I get PDO to list Array with Correct Types?

Asked

Viewed 69 times

0

In Mysql save data to a table by setting some fields as int or float, but when I make a select in the database via PDO array Everything comes as a string. Has some function that forces you to return the type according to what is in the bank?

Behold:

 array(13) {
  ["id"]=>
  string(4) "1713"
  ["id_shop_default"]=>
  string(1) "5"
  ["id_envio_default"]=>
  string(3) "200"
  ["regiao"]=>
  string(19) "SAO PAULO - CAPITAL"
  ["cep_inicio"]=>
  string(9) "01000-001"
  ["cep_fim"]=>
  string(9) "05999-999"
  ["peso_inicial"]=>
  string(5) "0.000"
  ["peso_final"]=>
  string(5) "1.000"
  ["valor"]=>
  string(5) "22.70"
  ["prazo_entrega"]=>
  string(1) "7"
  ["ad_valorem"]=>
  string(4) "1.00"
  ["kg_adicional"]=>
  string(4) "1.72"
  ["created"]=>
  string(19) "2016-09-19 17:11:09"
}

the same value is float!

Thanks in advance.

Edit:

<?php    

try{    

  $opt = array(PDO::ATTR_STRINGIFY_FETCHES => false);

  // Faz conexão com banco de daddos
  $pdo = new PDO("mysql:host=127.0.0.1;dbname=banco","root", "123456", $opt);


}catch(PDOException $e){
  // Caso ocorra algum erro na conexão com o banco, exibe a mensagem
  echo 'Falha ao conectar no banco de dados: '.$e->getMessage();
  die;
}

try {

  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    

  $consulta = $pdo->query("SELECT * FROM transportadora");
  $linha = $consulta->fetch(PDO::FETCH_ASSOC);    

  echo "<pre>";
  var_dump($linha);
  echo "</pre>";


} catch (PDOException $e) {
    echo $e->getMessage();
}
  • Put the code in which you create the PDO.

  • @rray I edited the Post and put the complete code already with the modifications, but without success, I thank you.

  • Check phpinfo() to see if you have mysqlnd installed.

1 answer

1


Check whether PDO::ATTR_STRINGIFY_FETCHES is marked as false this option can be applied via setAttribute() or directly in the PDO constructor.

$opt = array(PDO::ATTR_STRINGIFY_FETCHES => false);
$pdo = new PDO('mysql:host=localhost;dbname=base', 'usuario', 'senha', $opt);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.