返回从PHP到Android的特定数量的值

时间:2012-12-27 13:59:56

标签: php android mysql json

我的android代码遇到了麻烦。我正试图在Android中绘制图表。我想使用PHP脚本连接到MySQL库。我正在尝试向脚本发送一些参数,但它一直返回null。 PHP代码:

<?

mysql_connect(...);
mysql_select_db("temperature");

$Vreme = $_POST['Vreme'];
$Datum = $_POST['Datum'];

$q = mysql_query("SELECT * FROM temperature WHERE 
           ((datum > $Datum) || (datum = $Datum)) && (vreme > $Vreme) ");
while($e = mysql_fetch_assoc($q))
    $output[] = $e;

print(json_encode($output));

mysql_close();
?>

Android代码:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Vreme",s1));
nameValuePairs.add(new BasicNameValuePair("Datum",s2));
InputStream is = null;
try {
    String adresa="http://senzori.open.telekom.rs/grafik.php";
    HttpPost httppost = new HttpPost(adresa);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
}
catch(Exception e) {
    Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    result = sb.toString();

}
catch(Exception e) {
    Log.e("log_tag", "Error converting result "+e.toString());
}

2 个答案:

答案 0 :(得分:1)

评论的组合:

1:更改为mysqli或pdo(请参阅Advantages Of MySQLi over MySQL

2:阻止sql注入(参见https://stackoverflow.com/tags/php/info中途)

另外,在查看代码时,不要在日期周围使用引号(如果不是数字,则使用vreme)。尝试

"SELECT * FROM temperature WHERE (datum>='$Datum' && vreme>'$Vreme')"

如果它无法在常规浏览器中测试您的页面以确保PHP部分正常工作。您还可以添加一些var_dump()来检查值。

答案 1 :(得分:0)

您应该尝试单独调试各个部分。

  1. 尝试使用普通浏览器连接到您的php页面。如果它工作,你知道错误在你的java代码中。如果它不起作用你可以暂时保留java代码并专注于使php页面工作。
  2. Datum和Vreme的硬编码有效值,看看在离开POST部分时php代码是否有效。
  3. 在mysql中尝试查询,看看它在投入php之前是否达到预期效果。
  4. 启用general query log以查看php发送给mysql的内容。
  5. 这样你就会指出错误。