我正在玩我发现here的代码。我只能让我的数据库返回一个空的json对象。这是我的代码。
public class TableTalkSplash extends Activity {
private InputStream is;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = "";
InputStream is = null;
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("row_id","1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/myscript.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();
System.out.println(result); // this is printing "null" to the console
}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.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString()); //exception is being caught here
}
}
}
这是我的php脚本。
<?php
mysql_connect("host","username","password");
mysql_select_db("mydb");
$q=mysql_query("SELECT * FROM dinner_info WHERE row_id ='".$_REQUEST['row_id']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
我有一个当前正在运行网站的apache webserver,而.php文件与index.html文件位于同一目录中。我有一个mySQL数据库,它运行在与apache服务器相同的盒子上。我对数据库知之甚少,但我知道当我运行SELECT * FROM dinner_info时WHERE row_id = 1;它返回正确的信息。所以我猜我的错误是在PHP中。我尝试用localhost替换“host”,用我的用户名替换“username”,用我的密码替换“password”。有任何想法吗?如果您需要更多信息,请告诉我们!谢谢大家。
答案 0 :(得分:0)
我猜测数据库连接或查询失败尝试这个来帮助调试:
<?php
error_reporting(-1);
ini_set("display_errors", 1);
mysql_connect("host","username","password") or die('Could not connect: ' . mysql_error());;
mysql_select_db("mydb");
$query = "SELECT * FROM dinner_info WHERE row_id ='".mysql_real_escape_string($_REQUEST['row_id'])."'"
$q=mysql_query($query);
if (!$q) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();