douhuang9886
douhuang9886
2019-07-06 00:50

为什么JSON没有显示数据

已采纳

Error when using some.php?id=$id

I have table named tb_syarat_layanan. When I try to get JSON, array it shows no Data.

<?php

 //Importing database
 require_once('koneksi.php');

 $query = "select * from tb_syarat_layanan WHERE id_layan=$id";
 $hasil = mysqli_query($con,$query);

 if(mysqli_num_rows($hasil) > 0 )
 {
     $response = array();
     $response["data"] = array();
     while($x = mysqli_fetch_array($hasil)) 
     {
         $h['id_layan'] = $x["id_layan"];     
         $h['dokumen'] = $x["dokumen"];
         array_push($response["data"], $h);
     }
     echo json_encode($response);
 }
 else 
 {
     $response["message"] = "No Data";
     echo json_encode($response);
 }

?>

But when I set my $query like this :

$query = "select * from tb_syarat_layanan WHERE id_layan=1";

it show the data that I want

JSON shows no data when $query is set with variable $id

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dsqbkh3630 dsqbkh3630 2年前

    The problem is how you are getting the id from the URL. Data sent on query string are stored inside $_GET

    $id = $_GET['id'];
    $query = "SELECT * FROM tb_syarat_layanan WHERE id_layan = $id";
    
    点赞 评论 复制链接分享
  • douping6871 douping6871 2年前

    Let's say you have some.php?id=1 in the URL. You need a way to get that id parameter from the query string. In PHP, this can be done easily using the $_GET superglobal. $_GET allows you to access the values passed in the query string.

    So in your code, you can do something like:

      $id = $_GET['id'];
    

    The best practice is to escape any input passed in the query string:

     $id = htmlspecialchars($_GET['id']);
    

    But if you aren't outputting that input anywhere in the page where it can be executed, and you aren't storing the query parameters for output later, this shouldn't be a problem. The only real danger here would be SQL injection. The best method for avoiding this would be to use prepared statements. See https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

    点赞 评论 复制链接分享

为你推荐