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!
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.
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.