我想使用用户名从用户表中检索数据,但它无法正常工作这里是我的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();
}
没有错误,但它无法检索任何数据是什么问题?
答案 0 :(得分:1)
请从php而不是Array返回json对象 我已将echo部分传递给json_encode(数组(&#39;响应&#39; =&gt; $ output,&#39;代码&#39; =&gt; $ flag [&#34;代码&#34;]));
<?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变量更改为结果。
答案 1 :(得分:0)
我刚刚解决了问题结果没有用,换句话说它无法通过数组获取数据而我只是把数组函数现在运行正常: - )