0

我正在编写一个 android 应用程序来检索属于特定用户的数据。我在 Activity2 中使用 Activity1 的 SharedPreference。

这是我存储在 Activity1 中的 SharedPreference

SharedPreferences sp = getSharedPreferences("login details", 0);
SharedPreferences.Editor spedit = sp.edit();
spedit.putString("sPhone",sPhone);              
spedit.putString("sPassword", sPassword);
spedit.commit();

我在 Activity2 中使用上述 SharedPreference 并将其作为字符串发送到 PHP 文件: Activity2 代码:

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();
?>

但 SQL 查询返回“null”。我收到一条错误消息“未定义的变量输出”。由于这个空值,应用程序通过说“FATAL EXCEPTION AsyncTask #1”在模拟器上崩溃。

4

2 回答 2

1

您需要先在 PHP 中声明您的数组,然后再尝试为其附加一个值:

// ...

$output = array(); // Add this line
while($row=mysql_fetch_assoc($sql))
    $output[]=$row;

// ...

如果这样做,错误将消失,输出将不再是无效的 JSON。

但是,请注意,display_errors无论如何您都应该在生产中禁用,因为错误可能会暴露有关您的应用程序的信息,进而可能会将攻击向量暴露给恶意用户。

您还将请求内容类型设置为application/json,但您传递的数据的实际类型是application/x-www-form-urlencoded。PHP 不会解码您发送的数据,$_POST也不会被填充。更改请求内容类型:

httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
于 2013-04-10T15:06:46.267 回答
0

DaveRandom 所说的关于首先声明你的数组,但你也应该检查查询是否真的成功。是的,当您手动运行它时它可以工作,但这并不能保证其他地方出了问题,例如从您的 Android 客户端获取奇怪的数据。

例如:

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();

另外,停止使用mysql_*函数。Blah blah 弃用 blah SQL 注入,你知道整个歌舞......

于 2013-04-10T15:12:09.447 回答