Search code examples
phpjsonmysqliresultset

Echo rows in mysqli result without declaring column names?


How can I echo all the rows (as JSON) in the query result without declaring each column name? I.e without writing 'location_id' => $row['location_id'] and so on, like I have done below.

<?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.";
}

?>

Updated code. Now with parameterized prepared statements as recommended by @Dharman (thanks!). I get Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) on line 17. I'm running version 7.3 of PHP. What's wrong? And how should I echo $data so it's a JSON object like before?

<?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();

?>

Solution

  • fetch_assoc() already returns your data as an associative array therefore you don't need to do the association all over again.

    You can simply assign your results to your data. => $data[] = $row

    For a detailed explaination on how fetch_assoc() works. Here's the doc.