2016-09-21 59 views
-1

我需要显示多行数据并显示json数据。这里是我的代码:显示多行数据并显示json数据

<?php  
    $dinner_food_category=$_GET['DinnerFoodCategory']; 
    $conn = mysqli_connect("localhost","taig9_gen_user","GenAdmin1/Pass"); 
    if($conn) { 
     $select_database = mysqli_select_db($conn,"taig9_genumy"); 
     $select_query = "SELECT food_id,food_name,serving_type,serving_type_amount,singal_unit_weight FROM food_details WHERE category_id IN ('VEG00','VGB00','SUP00','CAK00')"; 
     $result = mysqli_query($conn, $select_query); 
     if (mysqli_num_rows($result) > 0) {       
      while($row = mysqli_fetch_assoc($result)) { 
       $foods_id=$row['food_id']; 
       $foods_name=$row['food_name']; 
       $foods_type=$row['serving_type']; 
       $foods_type_amount=$row['serving_type_amount']; 
       $singal_unit_weights=$row['singal_unit_weight']; 
      }   
      $data = array("FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights);   
     } 
     echo stripslashes(json_encode($data)); 
    }   
?> 
+0

'$数据[] = array'并把它放在'while' –

+0

添加问题描述和提正确的标签 – Shettyh

+0

'$ data [] = array();'在'while'之前,然后在'while'里面'$ data [] = $ row;'就是这样 –

回答

0

在你food_变量被覆盖的while每次迭代,经过while循环结束 - 你只有最后一行值。为了避免这种情况,你应该用[]符号添加变量$data一个while循环中:

while ($row = mysqli_fetch_assoc($result)) { 
    $data[] = array(
     "FoodId" => $row['food_id']; 
     "FoodNames" => $row['food_name']; 
     "FoodType" => $row['serving_type']; 
     "FoodAmount" => $row['serving_type_amount']; 
     "SingalUnitWeight" => $row['singal_unit_weight']; 
    ); 
}   
// using `stripslashes` is useless 
echo json_encode($data); 
0
if (mysqli_num_rows($result) > 0) { 
    $data = []; 
    foreach ($result as $row) { 
     $foods_id=$row['food_id']; 
     $foods_name=$row['food_name']; 
     $foods_type=$row['serving_type']; 
     $foods_type_amount=$row['serving_type_amount']; 
     $singal_unit_weights=$row['singal_unit_weight']; 
     $data[] = ["FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights];   
    } 
    echo stripslashes(json_encode($data)); 
}