在不声明列名的情况下回显 mysqli 中的行?

Echo rows in mysqli result without declaring column names?

如何在不声明每一列名称的情况下回显查询结果中的所有行(如JSON)?即不写 'location_id' => $row['location_id'] 等等,就像我在下面所做的那样。

<?php

require_once("./config.php"); //database configuration file
require_once("./database.php");//database class file

$location_id = isset($_GET["location_id"]) ? $_GET["location_id"] : '';

$db = new Database();

if (isset($_GET["location_id"])){
    $sql = "SELECT * FROM location WHERE location_id = $location_id";
} else {
    $sql = "SELECT * FROM location";
}

$results = $db->conn->query($sql);


if($results->num_rows > 0){

    $data = array();

    while($row = $results->fetch_assoc()) {
        $data[] = array(
        'location_id' => $row['location_id'],
        'customer_id' => $row['customer_id'],
        'location_id' => $row['location_id'],
        'location_name' => $row['location_name'],
        'payment_interval' => $row['payment_interval'],
        'location_length' => $row['location_length'],
        'location_start_date' => $row['location_start_date'],
        'location_end_date' => $row['location_end_date'],
        'location_status' => $row['location_status'],
        'sign_sides' => $row['sign_sides'],
        'variable_annual_price' => $row['variable_annual_price'],
        'fixed_annual_price' => $row['fixed_annual_price'],
        'location_file' => $row['location_file']);
    }

header("Content-Type: application/json; charset=UTF-8");

echo json_encode(array('success' => 1, 'result' => $data));

} else {
    echo "Records not found.";
}

?>

更新代码。现在使用@Dharman 推荐的参数化准备语句(谢谢!)。我在第 17 行得到 Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)。我是 ​​PHP 的 运行 7.3 版。怎么了?我应该如何回显 $data 才能像以前一样成为 JSON 对象?

<?php

header("Content-Type: application/json; charset=UTF-8");

//include required files in the script
require_once("./config.php"); //database configuration file
require_once("./database.php");//database class file

$object_contract_id = isset($_POST["object_contract_id"]) ? $_POST["object_contract_id"] : '';

//create the database connection
$db = new Database();

if (isset($_POST["object_contract_id"])){
    $sql = "SELECT * FROM object_contract WHERE object_contract_id = ?";
    $stmt = mysqli->prepare($sql);
    $stmt->bind_param("s", $_POST['object_contract_id']);

} else {
    $sql = "SELECT * FROM object_contract";
    $stmt = mysqli->prepare($sql);
}

$stmt->execute();

$data = $stmt->get_result()->fetch_all();

?>

fetch_assoc() 已经 returns 您的数据作为关联数组,因此您不需要重新进行关联。

您可以简单地将结果分配给数据。 => $data[] = $row

有关 fetch_assoc() 工作原理的详细说明。这是 doc.