0
我有一個小問題實現一個程序,檢查一個值的MySQL數據庫,然後根據值的存在返回「True」或「False」。我能得到PHP使用下面的代碼(在這個例子中「A」即開始)返回值(它也顯示在Java日誌中的匹配行):從PHP到Android的布爾HTTP響應
<?php
mysql_connect("host","username","password");
mysql_select_db("Deal");
$sql=mysql_query("select * from CITY where CITY_NAME like 'A%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
我只是想檢查查看是否有滿足查詢條件的一條記錄(本例中以「A」開頭的一個城市),然後返回「True」或「False」並將其打印到ddms日誌中。
我一直在嘗試實現類似以下的內容,但是我沒有返回任何東西。
<?php
mysql_connect("host","username","password");
mysql_select_db("Deal");
$sql = mysql_query("select * from CITY where CITY_NAME like 'A%'") or die(mysql_error());
if ($sql) {
if(mysql_num_rows($sql) == 0) {
$row = "False";
print(json_encode($row);
mysql_close();
}
else {
$row = "True";
//while($row = mysql_fetch_assoc($sql))
//$output[]=$row;
print(json_encode($row);
//print(json_encode($output));
mysql_close();
}
}
?>
這裏是我的Android代碼:
public class CityActivity extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
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());
}
//paring datag
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
String myString ="";
json_data = jArray.getJSONObject(i);
int ct_id = json_data.getInt("CITY_ID");
String ct_name = json_data.getString("CITY_NAME");
myString = Integer.toString(ct_id);
Log.i(ct_name, myString);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
如果您有任何建議,請讓我知道。我真的很感激它。謝謝!