致命错误:未捕获错误:在bool

时间:2019-07-19 19:19:15

标签: php postgresql

我尝试使用PHP从PostgreSQL访问数据库。 我运行此代码,但出现错误:

VM6722:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.success ((index):58)
    at c (jquery-3.4.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.4.1.min.js:2)
    at l (jquery-3.4.1.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery-3.4.1.min.js:2)

我想弄清楚,但是我对php很陌生。因此,我将感谢您提供任何解决此问题的建议。

<?php

$db = new PDO('pgsql:host=localhost;dbname=webmap103;', 'postgres', 'postgres');
$sql = $db->query("SELECT id, name, image, web, category,ST_AsGeoJSON(geom, 5) as geom FROM cdmx_attractions ORDER BY name");
$features = [];

while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
    $feature = ['type'=>'Feature'];
    $feature['geometry'] = json_decode($row['geom']);
    unset($row['geom']);
    $feature['properties'] = $row;
    array_push($features, $feature);
}
$featureCollection = ['type'=>'FeatureCollection', 'features'=>$features];
echo json_encode($featureCollection);
?>

我希望在Web应用程序上显示数据。 我正在使用html和ajax来调用php,以便在PostgreSQL上访问我的数据库。

2 个答案:

答案 0 :(得分:0)

如果您的sql语句失败,git merge --continue返回$db->query(...)。检查您的sql语句是否有效并正确执行。如果它是false,则会收到错误“致命错误:未捕获的错误:在bool上调用成员函数fetch()”

答案 1 :(得分:0)

  

PDO :: query()返回PDOStatement对象,如果失败则返回FALSE。

  • 请勿使用Ajax调用您的PHP,至少要进行调试。看到错误会更容易。只需在浏览器中直接调用PHP路由即可。 json太糟了,无法在浏览器控制台中进行调试。

  • 尝试捕获错误并使用PHP进行显示:

<?php
    try{
        $db = new PDO('pgsql:host=localhost;dbname=webmap103;', 'postgres', 'postgres');
        $sql = $db->query("SELECT id, name, image, web, category,ST_AsGeoJSON(geom, 5) as geom FROM cdmx_attractions ORDER BY name");
        $features=[];
        while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
        $feature=['type'=>'Feature'];
        $feature['geometry']=json_decode($row['geom']);
        unset($row['geom']);
        $feature['properties']=$row;
        array_push($features, $feature);
        }
        $featureCollection=['type'=>'FeatureCollection', 'features'=>$features];
        echo json_encode($featureCollection);
    } catch (Exception $e) {
        var_dump($e->getMessage());
        var_dump($e->getCode());
    }
}
?>
  • 检查您的PHP日志(我不知道您的OS或PHP版本是什么,但这是使用PHP7.3-FPM的debian快速示例:
tail -f /var/log/php7.3-fpm.log

调用您的页面并观看您的外壳。

相关问题