The code below works fine everytime (returning null if nothing is found etc.) but when the id is "1" I dont get anything (the echo is blank).
I've tried with id "1" through "10" and "1" is the only one not working. I've tried casting id to INT.
Work: ...getGym.php?id=1
Do not work: ...getGym.php?id=2
<?php
//Getting the requested id
$id = $_GET['id'];
//Importing database
require_once('dbConnect.php');
//Creating sql query with where clause to get an specific gym
$sql = "SELECT * FROM gyms WHERE gymID = '$id'";
//getting result
$r = mysqli_query($con,$sql);
//pushing result to an array
$result = array();
$row = mysqli_fetch_array($r);
array_push($result,array(
"gymID" =>$row['gymID'],
"gymName" =>$row['gymName'],
"gymAddress" =>$row['gymAddress'],
"visitorsNow" =>$row['visitorsNow'],
));
//displaying in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
EDIT:
Mysql output:
mysql> SELECT * FROM gymplaneraren.gyms WHERE gymID = 1;
+-------+--------------------------------+-----------------+-------------+
| gymID | gymName | gymAddress | visitorsNow |
+-------+--------------------------------+-----------------+-------------+
| 1 | Friskis & Svettis Lackarebäck | Bergfotsgatan 1 | 50 |
+-------+--------------------------------+-----------------+-------------+
1 row in set (0.00 sec)
I have, after some suggestions, changed the code to be more secure. It still doesn't return any value for gymID = 1. New code below:
<?php
// Getting the requested id
$id = intval($_GET['id']);
// Importing database
require_once('dbConnect.php');
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM gymplaneraren.gyms WHERE gymID = ?";
if ($stmt = $con->prepare($query)) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($gymID,$gymName,$gymAddress,$visitorsNow);
while ($stmt->fetch()) {
$output[]=array($gymID,$gymName,$gymAddress,$visitorsNow);
}
echo json_encode($output);
}
mysqli_close($con);