我刚开始编写web服务,似乎无法理解这一点!我有一个简单的phprestful服务,它返回json响应,但响应中没有任何键(我不知道这是否是正确的术语)。我得到的是这样的东西。
(
(
"name",
qty,
"image",
"price",
"date"
)
我确信我在这里做错了什么。
这是我的服务:
<?php
header('Content-type: application/json');
class InventoryAPI {
private $db;
function __construct() {
$this->db = new mysqli('localhost', 'user', 'pass', 'dbname');
$this->db->autocommit(FALSE);
}
function __destruct() {
$this->db->close();
}
function checkInv() {
$query = "SELECT model, sku, quantity, stock_status_id, image, price, date_available FROM table_name";
$result = $this->db->query($query);
$rows = array();
$i = 0;
while($row = $result->fetch_row())
{
$rows[] = $row;
$i++;
}
$result->close();
$this->db->close();
echo json_encode($rows);
}
}
$api = new InventoryAPI;
$api->checkInv();
?>
我假设您希望使用fetch_assoc()而不是fetch_row()。fetch_assoc()将返回一个数组,该数组的键与列的名称相同。fetch_row()将返回一个基于列位置的枚举数组。例如:model为0,sku为1。
您可以通过打印数组来测试这一点。
while($row = $result->fetch_row())
{
print_r($row);
}