我是PHP的绝对初学者。我目前正在开发一个Android应用程序,该应用程序有一个使用PHP的Web服务。我需要获得2个执行的SQL查询的结果,并将其转换为json。我的问题是我没有得到任何结果回到客户,我也没有得到任何错误。我想这是因为我把结果分成了两个数组。我如何将两个查询的结果保存为一个数组,也就是一个json响应?
代码编辑:
<?php
$host = "localhost"; // host of MySQL server
$user = "root"; // MySQL user
$pwd = ""; // MySQL user's password
$db = "food"; // database name
// Create connection
$con = mysqli_connect($host, $user, $pwd, $db);
// Check connection
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
//$uname = $_POST['uname'];
// query the application data
$sql = "SELECT * FROM uploads WHERE status = '0' ORDER By precious_time DESC";
$sql2 = "SELECT * FROM uploads_avatar WHERE uname = 'sinii'";
$result = mysqli_query($con, $sql);
$result2 = mysqli_query($con, $sql2);
// an array to save the application data
$rows = array();
$rows2 = array();
// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
// iterate to query result and add every rows into array
while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$rows2[] = $row2;
}
$result_merge = array_merge($rows, $rows2);
// close the database connection
mysqli_close($con);
// echo the application data in json format
echo json_encode($result_merge);
?>
然而,我在没有第二个查询的情况下使用第二个数组等运行应用程序,然后它就可以工作了,但我也需要第二个询问的数据。
谢谢你的帮助!
要在一个数组中获取值,请使用array_merge合并两个数组,也可以使用这种格式的
$jsonResult = array();
while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$jsonResult["uploads"][] = $row;
}
while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$jsonResult["upload_avatar"][] = $row2;
}
echo json_encode($jsonResult);
使用阵列合并
$jsonResult = array_merge($rows, $rows2);
echo json_encode($jsonResult);
至于json响应,您应该首先通过在web浏览器中查看响应来检查响应。
为什么不在查询时使用MySQL查询来合并这两个表??
从上传中选择*,uploads_avatar其中uploads.status="0"和uploads_avatar.uname="sinii";