dtpn60029 2016-04-06 09:22
浏览 82
已采纳

使用PHP从MYSQL获取数据不会返回任何结果

So I am using this tutorial: https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ to try and get data from my local MYSQL server (using Wamp64). I had the undefined index error at first, which I fixed using the isset() statement. But now it just returns:

{"result":[]}

I have, however, a lot of data in the set column of that database. Here is the code:

<?php
//Getting the requested klas
$klas = isset($_GET['klas']) ? $_GET['klas'] : '';

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

//Creating SQL query with where clause to get a specific klas
$sql = "SELECT * FROM lessen WHERE klas='$klas'";

//Getting result
$r = mysqli_query($con,$sql);

//Pushing result to an array
$result = array();
while ($row = mysqli_fetch_array($r)) {
    array_push($result,array(
    "id"=>$row['id'],
    "klas"=>$row['klas'],
    "dag"=>$row['dag'],
    "lesuur"=>$row['lesuur'],
    "les"=>$row['les'],
    "lokaal"=>$row['lokaal']
    ));
}

//Displaying the array in JSON format
echo json_encode(array('result'=>$result));

mysqli_close($con);
?>

I tried out the

SELECT * FROM lessen WHERE klas='$klas'

statement in my database and it seems to return the correct data. Any idea what is causing this?

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dqk77945 2016-04-06 09:54
    关注

    Point 1 is:

    isset function only checks if klas is set in the $_GET global array. So if somehow $klas is blank - your query will return empty (without giving error).

    So please check values in the $_GET and possibly from where it is accessed. Or you can add condition to avoid empty query like --

    if (!empty($_GET['klas'])) {
    // rest of the code block upto return
    

    Point 2 is:

    You have mentioned if you echo the sql it returns

    SELECT * FROM lessen WHERE klas=''{"result":[]} 
    

    Here the second part (the JSON) is from echoing the result at the end of your code. So for the first part (i.e. echoing $sql) we see that klas=''. That actually goes to the Point 1 as mentioned above.

    So finally you have to check why the value at $_GET is showing blank. That will solve your problem.

    UPDATE:

    From @GeeSplit's comment For the request

    "GET /JSON-parsing/getKlas.php?=3ECA"

    There will be nothing in $_GET['klas'] cause the querystring in the url doesn't contain any key.

    So either you have to change the source from where the file is called. Or you can change how you are getting the value of klas.

    Example:

    $tmpKlas = $_SERVER['QUERY_STRING'];
    $klas = ltrim($tmpKlas, '=');
    

    Rest of your code will work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器