Skip to content
Advertisement

PDO FetcthAll to JSON null

I’m creating a APIRest in Angular and I need to parse PHP results to JSON. I read some answer about this problem, but didn’t resolve my problem.

The problem is the json_encode return null, and i don’t know why.

$conexion = new PDO("mysql:host=localhost;dbname=blog", "root", "");
$sql = "select * from articles";
$sql = $conexion->prepare($sql);
$json = json_encode($sql->fetchAll(PDO::FETCH_ASSOC));

if ($json) {
    echo $json;
} else {
    echo "Error";
    echo "<pre>";
    print_r($json);
    echo "</pre>";
}

Advertisement

Answer

For JSON you need utf-8 encoded data, thus you have to tell PDO that

$conexion = new PDO("mysql:host=localhost;dbname=blog;charset=utf8mb4", "root", "");
$sql = $conexion->query("select * from articles");
echo json_encode($sql->fetchAll(PDO::FETCH_ASSOC));

the rest of code makes no sense and should be removed.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement