echo json_decode()仅返回方括号

时间:2018-09-12 20:55:15

标签: php sql json

我试图从MySQL查询中获取JSON对象,以便在使用JavaScript的select中添加选项元素。

我的PHP代码是:

$carrera = $_GET['idcarrera'];

require_once("inc/config.php"); 
$pdo = conexionPDO();
$sql = "SELECT  materias.clave, materias.nombre FROM carreras_plan
            inner join carreras_plan_materia on carreras_plan.clave = carreras_plan_materia.clave_carrera
            inner join materias on carreras_plan_materia.clave_materia = materias.clave
            where carreras_plan_materia.clave_carrera like $carrera;";
    $ps = $pdo->prepare($sql);
    $ps->execute();

    $data = $ps->fetchAll(PDO::FETCH_ASSOC);
    $json_data = json_encode($data, true);
    echo $json_data;

如果获取JSON并使用console.log,则会在控制台中获取查询结果。但是,如果我擦除echo $json_data;,则在尝试将字符串解析为JSON时会遇到下一个错误:

Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

我认为发生这种情况是因为echo $json_data;仅将方括号括起来:

enter image description here

有人可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用准备好的语句,并且还应该检查查询结果。您怎么知道它是否失败?

$carrera = $_GET['idcarrera'];

require_once("inc/config.php"); 
$pdo = conexionPDO();
$sql = "SELECT  materias.clave, materias.nombre FROM carreras_plan
        inner join carreras_plan_materia on carreras_plan.clave = carreras_plan_materia.clave_carrera
        inner join materias on carreras_plan_materia.clave_materia = materias.clave
        where carreras_plan_materia.clave_carrera like ?";
if ($ps = $pdo->prepare($sql)) {
    if ($ps->execute([$carrera])) {
        $data = $ps->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $data = ["error"=>"execute failed"];
    }
} else {
    $data = ["error"=>"prepare failed"]
}
$json_data = json_encode($data);
echo $json_data;