我一直在試用各種網站上顯示的使用php連接到MySQL數據庫的教程。我不知道下面的代碼有什麼問題。任何人都可以告訴我我需要做什麼。將android應用程序連接到mysql數據庫
這是我的PHP代碼
<?php
mysql_connect("localhost","root","sugi");
mysql_select_db("android");
$q=mysql_query("SELECT * FROM people
WHERE
birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close(); ?>
這是我的SQL查詢
CREATE TABLE `people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR(100) NOT NULL ,
`sex` BOOL NOT NULL DEFAULT '1',
`birthyear` INT NOT NULL
)
這是Android
public class main extends Activity {
InputStream is;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1990"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
//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");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
}
}
程序做工精細我的Java代碼。但我不能連接到http://localhost/index.php
。程序顯示失敗3次。可以幫我看看我哪裏出錯了?
感謝大家的幫助。現在我可以連接到MySQL。但我不能得到json數據的價值。編制敬酒信息2通和1失敗。誰能幫我?下面的圖片是當我在我的IE中鍵入http://localhost/index.php
。而第6行是這一切
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
我不知道我哪裏出錯了。
我對PHP一無所知,但是我發現你的請求有正確的答案:JSON對象數組。可能PHP腳本工作正常。 – 2011-04-05 07:22:40