return tinyint as boolean in json encode

0

I do a fetchall with pdo in the database and I get the result correctly, but the boolean values are saved in tinyint in the database, and I get them in 1 and 0, so when I do json encode, it returns 0 and 1, I wanted to return true or false. I tried to make a foreach to convert but so it returns only the line I converted.

$usermail = $request->getHeader('PHP_AUTH_USER');
$senha = $request->getHeader('PHP_AUTH_PW');

$sql = new Sql();
$user =  new Usuario();
$autenticado = $user->login($usermail[0],$senha[0]);

if ($autenticado) {
    $resultado = $sql->select("SELECT * FROM tb_alunos WHERE email = :EMAIL LIMIT 1",array(
        ":EMAIL"=>$usermail[0]
    ));
    foreach( $resultado as $row ) {
        $array[] = array('liberadoexercicio' => (bool)$row['liberadoexercicio']);
    }
    $response = json_encode(array_shift($array),JSON_NUMERIC_CHECK);
    return $response;
}else{
    return $response->withStatus(401);
}
    
asked by anonymous 03.01.2018 / 14:47

2 answers

1

The error is that basically what you're doing is capturing all information from the tb_alunos > Saving only liberadoexercicio data in variable $array > Deleting the first record with array_shift and displaying json on the screen.

You can do the following to return the data as bool

<?php

$resultado = $sql->select("SELECT * FROM tb_alunos WHERE email = :EMAIL LIMIT 1",array(
    ":EMAIL"=>$usermail[0]
));

/* Se você quiser retornar apenas o campo 'liberadoexercicio' utilize a query abaixo (é melhor quanto a performance) */
/* SELECT liberadoexercicio FROM tb_alunos WHERE email = :EMAIL LIMIT 1 */

foreach( $resultado as &$row ) {
    $row["liberadoexercicio"] = (bool)$row["liberadoexercicio"];

    //$row["liberadoexercicio"] = $row["liberadoexercicio"] == 1; // Outra forma
}

echo json_encode($resultado);
  

& means that $row is a reference to a variable, as I do not know your level of object orientation, I'll leave the link to read .

    
03.01.2018 / 14:56
0

You can check when you set the array, using a conditional (if, switch, ternary)

$usermail = $request->getHeader('PHP_AUTH_USER');
$senha = $request->getHeader('PHP_AUTH_PW');

$sql = new Sql();
$user =  new Usuario();
$autenticado = $user->login($usermail[0],$senha[0]);

if ($autenticado) {
    $resultado = $sql->select("SELECT * FROM tb_alunos WHERE email = :EMAIL LIMIT 1",array(
        ":EMAIL"=>$usermail[0]
    ));
    foreach( $resultado as $row ) {
        // modo 1
        if($row['liberadoexercicio'] == 1)
            $res = true;
        else
            $res = false;
        $array[] = array('liberadoexercicio' => $res);  
        // modo 2
        $array[] = array(
            'liberadoexercicio' => ($row['liberadoexercicio'] == 1) ? true : false
        );
    }
    $response = json_encode(array_shift($array),JSON_NUMERIC_CHECK);
    return $response;
}else{
    return $response->withStatus(401);
}
    
03.01.2018 / 14:54