简体   繁体   English

PHP Rest Web服务响应

[英]PHP Rest Web Service Response

I am new to writing web services and I cannot seem to figure this out! 我是写Web服务的新手,似乎无法弄清楚! I have a simple php restful service that returns a json response, but I don't have any keys in the response (I don't know if that's the right term) What I get is something like this. 我有一个简单的php restful服务,它返回json响应,但是响应中没有任何键(我不知道这是否是正确的术语)。我得到的是这样的东西。

(
    (
    "name",
    qty,
    "image",
    "price",
    "date"
)

I am positive I am doing something wrong here. 我很肯定我在这里做错了。

Here is my service: 这是我的服务:

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

?>

I'm assuming you will want to use fetch_assoc() instead of fetch_row(). 我假设您将要使用fetch_assoc()而不是fetch_row()。 fetch_assoc() will return an array with keys the same name as the columns. fetch_assoc()将返回一个数组,其键的名称与列的名称相同。 fetch_row() will return an enumerated array based on the column position. fetch_row()将根据列位置返回一个枚举数组。 For example: model is 0, sku is 1. 例如:model为0,sku为1。

You can always test this out by printing out the array. 您始终可以通过打印出阵列来进行测试。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM