【发布时间】:2011-07-28 16:33:55
【问题描述】:
我一直在尝试各种网站上显示的关于使用 php 将 MySQL 数据库连接到 android 的教程。我不知道我下面的代码有什么问题。谁能告诉我我需要做什么。
这是我的 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中的java代码
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();
}
}
}
程序运行良好。但我无法连接到http://localhost/index.php。程序显示失败 3 次。能帮我看看哪里出错了吗?
感谢大家的帮助。现在我可以连接到mysql了。但我无法获得 json 数据的值。 prog toast a msg 2 pass and 1 failed。谁能帮我?下图是我在 IE 中输入 http://localhost/index.php 时的图像。第 6 行就是这一切
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
我不知道我哪里错了。
【问题讨论】:
-
我对 PHP 一无所知,但我看到您对您的请求有正确的答案:JSON 对象数组。可能php脚本工作正常。