duanjing9739 2016-10-14 15:04
浏览 49
已采纳

PDO FetcthAll到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>";
}
  • 写回答

1条回答 默认 最新

  • douxiaqin2062 2016-10-14 15:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?