在 mysqli 结果中回显行而不声明列名



如何在不声明每个列名的情况下回显查询结果中的所有行(作为 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()已经将数据作为关联数组返回,因此您无需重新进行关联。

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

有关fetch_assoc()如何工作的详细解释。这是文档。

相关内容

  • 没有找到相关文章

最新更新