我想使用用户名从用户表中检索数据,但它无法正常工作,这是我的 php 代码:
<?php
mysql_connect("xxx","xxx","xxx");
mysql_select_db("xxx");
$username = $_POST["name"];
$sql = mysql_query("select * from user where username = '$username'");
$flag["code"] = 0;
$check = mysql_fetch_row($sql);
if ($check > 0)
{
$flag["code"] = 1;
echo json_encode($flag);
while ($row= mysql_fetch_assoc($sql))
{
$output[] = $row;
}
}
echo json_encode($output);
mysql_close();
?>
这是我的 Java 代码:
try
{
JSONObject json = new JSONObject(result);
code = (json.getInt("code"));
if (code == 1)
{
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++)
{
JSONObject jsonObject = array.getJSONObject(i);
firstname = jsonObject.getString("firstname");
et.setText(firstname);
}
}
}
catch (Exception e)
{
}
这是结果:
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line+"\n");
}
is.close();
result = sb.toString();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
没有错误,但无法检索任何数据,问题是什么?
最佳答案
请从 php 返回 json 对象而不是数组 我已将 echo 部分更改为 json_encode(array('response'=>$output,'code'=>$flag["code"]));
<?php
mysql_connect("xxx","xxx","xxx");
mysql_select_db("xxx");
$username = $_POST["name"];
$rs = mysql_query("select * from user where username = '$username'");
$flag["code"] = 0;
$check = mysql_num_rows($rs);
if ($check > 0)
{
$flag["code"] = 1;
while ($row= mysql_fetch_array($rs))
{
$output[] = $row;
}
}
echo json_encode(array('response'=>$output,'code'=>$flag["code"])); //changed here
mysql_close();
?>
现在在java中,
try
{
JSONObject json = new JSONObject(result);
code = (json.getInt("code"));
if (code == 1)
{
JSONArray array = json.getJSONArray('response');
for (int i = 0; i < array.length(); i++)
{
JSONObject jsonObject = array.getJSONObject(i);
firstname = jsonObject.getString("firstname");
et.setText(firstname);
}
}
}
catch (Exception e)
{
}
如果失败 JSONObject json = new JSONObject(result);不是必需的,因为结果已经是 json 对象。只需删除该行并将所有 json 变量更改为结果即可。
关于php - 如何使用json检索数据到mysql android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29135880/