php - 致命错误:未捕获的错误:在 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 上的数据库。
解决方案
如果您的 sql 语句失败,则$db->query(...)
返回false
. 检查您的 sql 语句是否有效并正确执行。如果是,false
您将收到错误“致命错误:未捕获的错误:调用 bool 上的成员函数 fetch()”
推荐阅读
- ruby - 如何从 zsh 安装和运行“hanami new bookshelf”
- twilio - 从 DialogFlow API 开始短信聊天
- python - numpy.polyfit 与 numpy.polynomial.polynomial.polyfit
- java - Android 模拟器设备文件资源管理器中的权限被拒绝
- sql - 在 SQL 中的数组内的结构内选择
- github - 如何使用 GitHub Actions On 的字符串进行事件配置?
- java - 如何将字符串中的每个单词大写(java)
- javascript - 经纬度到 XY,字面投影缩放级别
- python - 我的 Tensorflow/Keras 模型的最佳层模式是什么?
- c# - 如何发出静态外部方法?