显示空输出的PHP
我正在编写一个android应用程序,用于检索属于特定用户的数据。我在Activity2中使用Activity1的SharedReference 下面是我存储在Activity1中的SharedReference显示空输出的PHP,php,android,Php,Android,我正在编写一个android应用程序,用于检索属于特定用户的数据。我在Activity2中使用Activity1的SharedReference 下面是我存储在Activity1中的SharedReference SharedPreferences sp = getSharedPreferences("login details", 0); SharedPreferences.Editor spedit = sp.edit(); spedit.putString("sPhone",sPhone)
SharedPreferences sp = getSharedPreferences("login details", 0);
SharedPreferences.Editor spedit = sp.edit();
spedit.putString("sPhone",sPhone);
spedit.putString("sPassword", sPassword);
spedit.commit();
我在Activity2中使用上述SharedReference,并将其作为字符串发送到PHP文件:
活动2代码:
SharedPreferences prefs = getSharedPreferences("login details", 0);
String str = prefs.getString("sPhone", "");
nameValuePairs.add(new BasicNameValuePair("userid", str));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-type", "application/json");
response = httpclient.execute(httppost);
entity = response.getEntity();
is = entity.getContent();
以下是PHP代码:
<?php
mysql_connect("localhost","root","");
mysql_select_db("assigndroid");
header('content-type=application/json; charset=utf-8');
//$userID = isset($_POST['userid']) ? $_POST['userid'] : '';
$userID = mysql_real_escape_string($_POST['userid']);
$sql=mysql_query("select * from newassignment where issuedBy='$userID';");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
在尝试向数组添加值之前,需要用PHP声明数组:
// ...
$output = array(); // Add this line
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
// ...
如果这样做,错误将消失,输出将不再是无效的JSON
<>但是注意,在生产中,你应该禁用,因为错误可以公开你的应用程序的信息,而这些信息反过来又会向恶意用户公开攻击向量。
您还将请求内容类型设置为application/json
,但实际传递的数据类型是application/x-www-form-urlencoded
。PHP不会解码您发送的数据,并且不会填充$\u POST
。更改请求内容类型:
httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
DaveRandom所说的首先声明数组,但是您还应该检查查询是否确实成功。是的,当您手动运行它时,它可以工作,但这并不保证其他方面出了问题,比如从您的Android客户端获取奇怪的数据
例如:
另外,停止使用mysql.*
函数。废话废话,废话SQL注入,你知道整个过程…当你直接在数据库中运行查询时,它会返回值吗?@andrewsi,是的,当我在数据库中运行它时,它会返回值。然后我所能建议的就是你添加一些日志记录,看看它实际上传递了什么。例如,如果数据库中没有有效条目,它应该返回什么?“致命异常异步任务#1”通常表示您混淆了UI线程和非UI线程stuff@DaveRandom我做到了。它根本不提供任何输出。@SankarV Yes,将值附加到未声明的数组会隐式声明它。但它也会引发一个E_通知
,该通知在OP的系统上被输出,导致响应正文无效。此外,如果未声明数组,则最终将null
传递给json\u enocde()
,并生成E\u通知。即使这不是唯一的问题,也是一个问题。@user2201650如果查询返回0行,则您的实现将返回null。如果要获取空数组,必须遵循DaveRandom的answer@SankarV问题是android代码没有传递任何内容,我将“userid”传递给PHP代码。@user2201650这是因为您传递了URL编码的数据,但将请求的内容类型设置为application/json
。将请求的内容类型设置为application/x-www-form-urlencoded
。我会更新我的答案。
if( $sql = mysql_query("select * from newassignment where issuedBy='$userID';") ) {
while($row = mysql_fetch_assoc($sql)) {
$output[] = $row;
}
print(json_encode($output));
} else {
print(json_encode('query failed: ' . mysql_error()));
}
mysql_close();