php mysql从json中的mulitiple表中获取数据

时间:2017-05-02 07:32:01

标签: php mysql json

请帮助,我需要从两个表中获取数据,并在json我的表中编码

  1. Customers_table
  2.   

    id | inv_id | customer_name |地址| total_value

    1. Items_table
    2.   

      id | inv_id |描述|细节|数量| UNIT_PRICE

      我的PHP代码如下:

      <?php
      require "config.php";
      
      $sql = "SELECT customers_table.id,
                      customers_table.inv_id,
                      customers_table.customer_name,
                      customers_table.address,
                      customers_table.total_value,
                      items_table.inv_id,
                      items_table.description,
                      items_table.details,
                      items_table.inv_id,
                      items_table.qty,
                      items_table.ubit_price,
                      items_table.amount,
      
                      FROM customers_table INNER JOIN items_table ON
                      customers_table.inv_id = items_table.inv_id;";
      $result = mysqli_query($db, $sql);
      $response = array();
      
      while ($row = mysqli_fetch_array($result))
          {
          array_push($response);
          }
      
      echo json_encode(array(
          "server_response" => $response
      ));
      mysqli_close($db)
      ?>
      

      但是JSONLint响应是

      {
          "server_response": []
      }
      
      请问,我做错了什么?

1 个答案:

答案 0 :(得分:3)

array_push()接受两个参数,例如array_push($array, $element_to_be_pushed)array_push reference

您可以使用$array[]重写相同的代码,这会将新元素推送到下一个可用的索引。

试用此代码:

<?php
require "config.php";
$sql ="SELECT customers_table.id,
                customers_table.inv_id,
                customers_table.customer_name,
                customers_table.address,
                customers_table.total_value,
                items_table.inv_id,
                items_table.description,
                items_table.details,
                items_table.inv_id,
                items_table.qty,
                items_table.ubit_price,
                items_table.amount
                FROM customers_table INNER JOIN items_table ON
                customers_table.inv_id = items_table.inv_id;";
$result = mysqli_query($db, $sql);

$response = array();

while($row = mysqli_fetch_array($result))
{
    $response[] = $row;
}
echo json_encode(array("server_response"=> $response));
mysqli_close($db)
?>

更新回答:

额外的逗号“items_table.amount,”已删除。