简体   繁体   English

试图将 MySQL 查询的结果放入 JavaScript 数组

[英]Trying to get results of a MySQL query into a JavaScript array

I've got a MySQL database of offices with geo data.我有一个带有地理数据的办公室 MySQL 数据库。 I'm trying to get a list of the office cities into a JavaScript array.我正在尝试将办公城市列表放入 JavaScript 阵列中。 For now, I just wanted to set up a simple $.ajax() to log the list into the console, but it's returning null.现在,我只想设置一个简单的$.ajax()将列表记录到控制台,但它返回 null。 I'm just running my JavaScript function "query()" in console after the page loads.我只是在页面加载后在控制台中运行我的 JavaScript function “query()”。

Here's my JavaScript.这是我的 JavaScript。

function query() {
  $.ajax({
    url: "query.php",
    method: "POST",
    dataType: 'json',
    success: function(data) {
      let output = JSON.parse(data)
      console.log(output)
    }
  })
}

Here's query.php这里查询。php

<?php
include 'database.php';
$sql="SELECT `Office City` FROM `offices`";
$result = $link->query($sql);

if ($result) {
    while($row = $result->fetch_assoc()) {
        array_push($result_array, $row);
    }
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>

Here's database.php.这是数据库。php。 I'm able to write to MySQL using this PHP, so I assume it's correct.我可以使用这个 PHP 写入 MySQL,所以我认为它是正确的。

<?php
    $hostname = "hostus.mostus.com";
    $username = "name";
    $password = "pw";
    $database = "db";
    $link = mysqli_connect($hostname, $username, $password,$database);
    if (mysqli_connect_errno()) {
        die("Connect failed: %s\n" + mysqli_connect_error());
        exit();
     }

When I run query() in the console, it responds "undefined" then null.当我在控制台中运行query()时,它响应“未定义”然后 null。

Your sql is invalid.您的 sql 无效。 I would also init the $result_array before.我之前也会初始化 $result_array 。 Currently if the result is empty, you are returning null.目前,如果结果为空,则返回 null。

<?php
include 'database.php';
$sql="SELECT `Office`, `City` FROM `offices`";
$result = $link->query($sql);

$result_array = [];
if ($result) {
    while($row = $result->fetch_assoc()) {
        array_push($result_array, $row);
    }
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM