使用JSON管理来自多个表的数据(PHP + MySQL)
I'm currently working on a project that involves an Android app and MySQL. I need to get data from a MySQL database (Which is located on a local Server, I'm using Apache), the thing is, I've have already done this by getting data from a SINGLE table and then with a class that implements "Serializable" I'm able to "use" the data. Now, here is my .php working
<?PHP
include_once("connection.php");
$query = "SELECT E.Nombre, COUNT(C.Id_Estudiante_FK) AS Cuenta
FROM Estudiante E INNER JOIN Comentario C ON E.Id_Estudiante=C.Id_Estudiante_FK
GROUP BY E.Id_Estudiante
ORDER BY COUNT(C.Id_Estudiante_FK) DESC";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
echo json_encode($data);
?>
It returns back the data I need already encoded, my question is how can I manage that information I'm getting, is it possible to just create another class that implements Serializable having as attributes the rows I'm returning (Which are "Nombre" and "Cuenta")?
Here is the php I use for the query that only involves one table (Already works, and I'm able to "use" the data):
<?PHP
include_once("connection.php");
if(isset($_POST['txttipooferta'])){
$idtipooferta=$_POST['txttipooferta'];
$query = "SELECT * FROM oferta WHERE Id_Tipo_Oferta_FK=$idtipooferta AND Cupos>0 ORDER BY Id_Oferta DESC";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
echo json_encode($data);
}
?>
Would my problem be solved by just creating another class that implements Serializable and has as attributes "Nombre" and "Cuenta"?
Thank you!
As I stated in a comment before, this particular problem I had was a "plus" I would add to my project, I was focused on other more important parts of it therefore I did not have time to check on this. The answer is yes, you can just create a class that implements Serializable and matches the attributes you are encoding, below you can see my .php and my Java Class that work:
<?PHP
include_once("connection.php");
$query = "SELECT E.Nombre, COUNT(C.Id_Estudiante_FK) AS Cuenta
FROM Estudiante E INNER JOIN Comentario C ON E.Id_Estudiante=C.Id_Estudiante_FK
GROUP BY E.Id_Estudiante
ORDER BY COUNT(C.Id_Estudiante_FK) DESC";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
echo json_encode($data);
?>
The query returns two fields "Nombre" and "Cuenta".
And here you have my Java class
Hope this helps somebody else! :)