PHP休息Web服务响应

时间:2014-04-17 17:04:21

标签: php json web-services rest

我是编写Web服务的新手,我似乎无法解决这个问题!我有一个简单的php restful服务,它返回一个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();

?>

1 个答案:

答案 0 :(得分:0)

我假设你想要使用fetch_assoc()而不是fetch_row()。 fetch_assoc()将返回一个数组,其中的键与列的名称相同。 fetch_row()将根据列位置返回枚举数组。例如:model为0,sku为1。

您可以随时通过打印出阵列来测试它。

while($row = $result->fetch_row())
    {
        print_r($row);
    }