我按照教程通过 Android 应用程序中的 PHP 脚本连接到 MySQL 数据库。我的问题是(来自 LogCat):“未捕获的 TypeError:无法在 null:1 处调用未定义的方法 'select'”。我前段时间取得了成功,所以也许我无意中修改了导致这种情况的东西?在我的数据库中,有 4 列,这一侧一切正常。这是我的PHP代码:
<?php
$host="xxxxx"; // Host name
$username="xxxxx"; // Mysql username
$password="xxxxx"; // Mysql password
$db_name="xxxxx"; // Database name
$tbl_name="xxxxx"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$q=mysql_query("SELECT * FROM $tbl_name WHERE pass>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
...在 Android 上:
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","Pass1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MyWebsite/queryfromandroid.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);
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());
}
//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.getString("password")
);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
谢谢。