Hello I am new to Android. My problem is with my json
value:
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM textviewtable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row[] = $result->fetch_assoc())
{
$json = json_encode($row);
}
}
else {
echo "0 results";
}
echo $json;
$conn->close();
?>
JSON
[ {"id":"8","ServerData":"ABC","name":"xyz","pincode":"123456"}, {"id":"9","ServerData":"DEF","name":"JHG","pincode":"654321"}, {"id":"10","ServerData":"GHI","name":"KIH","pincode":"142536"} ]
The Json ServerData
, name
and pincode
objects are the same on each row but I need each row's ServerData
, name
and pincode
to be different.
So, for the first row I want to show ServerData
,name
, pincode
and for the second row I want to show ServerData1
, name1
, pincode1
etc. How can I do this?
The reason it's only showing one row is because in each loop you're just redefining the $json
variable. You need to store each row in an array and the echo that.
Try changing your code to:
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM textviewtable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = [];
//output data of each row
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo "0 results";
}
$conn->close();
Hope this helps!