El Hombre Sin Nombre El Hombre Sin Nombre - 11 days ago 5x
JSON Question

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

, 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>";
echo "</pre>";


When there are no variable to be used in the query, then there is no point in using prepare either - you can use query() method instead.

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

$conexion = new PDO("mysql:host=localhost;dbname=blog;charset=utf8", "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.