首页 > 解决方案 > 致命错误:未捕获的错误:在 bool 上调用成员函数 fetch()

问题描述

我尝试使用 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 上的数据库。

标签: phppostgresql

解决方案


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


推荐阅读