使用 JS 和 PHP SQL 查询获取 JSON 数据

问题描述 投票:0回答:1

function fetchBooks() {
  fetch('biblebooks.php')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => {
      // Handle the data retrieved from the server
      console.log(data); // Modify this to update your dropdown menus
    })
    .catch(error => {
      // Handle errors
      console.error('There was a problem with the fetch operation:', error);
    });
}

// Call the function to fetch data when needed
fetchBooks();
<?php


// Establish a connection to your database
require 'includes/dbh.inc.php';

// Execute your SQL query
$BookSQL = "SELECT DISTINCT book FROM translationTable";
$BookSTMT = $conn->prepare($BookSQL);
// $BookSTMT->bind_param("s", $UserID);
$BookSTMT->execute();
$BookRESULT = $BookSTMT->get_result();
// Run the query and fetch data

// Convert the data to JSON format
// $data = /* fetched data */;

header('Content-Type: application/json');
echo json_encode($BookRESULT);
?>

我能解释发生的事情的最好方法是用图片。我觉得答案就在我面前,但我已经在这个问题上坚持了几个小时了。

我正在开发一个圣经地址导航栏,其中的书籍和章节存储在 SQL 表中。数据应该显示在 3 个不同的下拉菜单中。

如果用户更改翻译,书籍和章节应反映表中找到的真实数据。

我收到以下与 json 相关的错误。我怎样才能让它工作并放置在正确的下拉列表中?

javascript php html sql json
1个回答
0
投票

$bookRESULT
不是可以以 JSON 形式返回的结果数组。您需要从中获取结果。

echo json_encode($BookRESULT->fetch_all(MYSQLI_ASSOC));
© www.soinside.com 2019 - 2024. All rights reserved.