mysql中的JSON无法通过PHP正确显示

mysql中的JSON无法通过PHP正确显示,php,mysql,json,Php,Mysql,Json,这是我在网上的mysql数据库 这是访问数据库以获取JSON文件的PHP文件,首先我选择表中的所有“category”单元格,然后循环遍历category,然后循环遍历category的其他列,并分配给$data2数组,然后将$data2和category分配给br一个$data数组,这就是我要显示的JSON <?php header("Access-Control-Allow-Origin: *"); $user = "u348833238_rest"; /* User */ $pa

这是我在网上的mysql数据库

这是访问数据库以获取JSON文件的PHP文件,首先我选择表中的所有“category”单元格,然后循环遍历category,然后循环遍历category的其他列,并分配给$data2数组,然后将$data2和category分配给br一个$data数组,这就是我要显示的JSON

<?php 
header("Access-Control-Allow-Origin: *");
$user = "u348833238_rest"; /* User */
$password = "a!23286029"; /* Password */
$dbname = "u348833238_rest"; /* Database name */
$host = "localhost";

$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
} 

// $sel = mysqli_query($con,"select * from restaurant");

// $data = array();

// while ($row = mysqli_fetch_array($sel)) {
//  $data[] = array("dishes" => ["name"=>$row['food'], "price"=>$row['price']] , "category"=>$row['category']);
// }
// echo json_encode($data);


$sel = mysqli_query($con,"select distinct category from restaurant");

$data = array();

while ($row = mysqli_fetch_array($sel)) {

    $c = $row['category'];

    $sel2 = mysqli_query($con,"select * from restaurant where category = $c ");

    $data2 = array();

    while ($row2 = mysqli_fetch_array($sel2)){
        $data2[] = array("name"=>$row2['food'], "price"=>$row2['price']);
    }

    // echo $data2;

    $data[] = array("category"=>$row['category'], "dishes"=>$data2);
}

// echo $data;
echo json_encode($data);

?>

属性“disks”数组为空时JSON如何正确显示,如下所示:


我建议打开“错误”,以便您可以看到问题所在

大概在这里:

select * from restaurant where category = $c
应该是:

select * from restaurant where category = '$c'

我想知道你为什么在回答中没有提到SQL注入,这是可能的。@RaymondNijland有相当多的问题是的,但我猜这不是一个严肃的项目。他们在他们的示例中也发布了看起来像真实MySQL数据的内容,所以我们只能做这么多。“所以我们只能做这么多。”互联网的问题是,糟糕的事情/教程/答案一直存在,而且可以发现几十年。这是一个非常受欢迎的(入门)程序员网站,至少警告(入门)程序员危险的不安全代码更多的人正在这样做。@ThomasEdwards这个悬而未决的问题是重复的。我建议你阅读关于防止不要做迭代查询的内容。使用连接。在使用数据库时,直接在query@mickmackusa中使用PHP变量始终使用准备好的语句,没有例外,即使您认为输入/数据是“安全的”。。事实上,如果用户有权访问
餐厅
表,则可以进行存储SQL注入。可能重复…和许多其他内容。也可通过以下方式关闭: