显示多个数据行并显示json数据

时间:2016-09-21 07:01:25

标签: php jquery html

我需要显示多个数据行并显示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));
    }           
?>

2 个答案:

答案 0 :(得分:0)

while的每次迭代中,您food_个变量都会被覆盖,并且在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);

答案 1 :(得分: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));
}