[英]Unable to connect to MySQL from Android using PHP
I am trying to connect to MySQL from an android device by following this tutorial: http://www.anddev.org/networking-database-problems-f29/connecting-to-mysql-database-t50063.html . 我正在尝试通过以下教程从Android设备连接到MySQL: http : //www.anddev.org/networking-database-problems-f29/connecting-to-mysql-database-t50063.html 。
All thats happening is that it is printing the ip address of the server I wish to connect to on the emulator. 所有发生的事情是它在模拟器上打印我想连接的服务器的IP地址。 It shows the following errors in the logcat: 它在logcat中显示以下错误:
12-08 11:42:01.993: I/dalvikvm(274): threadid=3: reacting to signal 3
12-08 11:42:02.113: I/dalvikvm(274): Wrote stack traces to '/data/anr/traces.txt'
12-08 11:42:03.273: E/log_tag(274): Error parsing data org.json.JSONException: Value
<!DOCTYPE of type java.lang.String cannot be converted to JSONArray
12-08 11:45:58.283: E/log_tag(351): Error parsing data org.json.JSONException: Value
<!DOCTYPE of type java.lang.String cannot be converted to JSONArray
12-08 11:53:11.302: E/log_tag(378): Error parsing data org.json.JSONException: Value
<!DOCTYPE of type java.lang.String cannot be converted to JSONObject
12-08 12:03:31.643: E/log_tag(405): Error parsing data org.json.JSONException: Value
<!DOCTYPE of type java.lang.String cannot be converted to JSONArray
12-08 12:20:57.052: E/log_tag(432): Error parsing data org.json.JSONException: Value
<!DOCTYPE of type java.lang.String cannot be converted to JSONArray
Below is a copy of my java file: 下面是我的java文件的副本:
package com.david.Connect;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ConnectActivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://86.47.59.249/employee.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("code","1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
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.getInt("EmployeeId")+
", name: "+json_data.getString("First_Name")+
", sex: "+json_data.getInt("Last_Name")+
", birthyear: "+json_data.getInt("Birth_Date")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
and here is my php file which I have on the server 86.47.59.29 where the MySQL Database is: 这是我的php文件,我在服务器86.47.59.29,其中MySQL数据库是:
<?php
mysql_connect("86.47.59.249","username","password");
mysql_select_db("Test");
$q=mysql_query("SELECT * FROM Tbl_Employee WHERE
EmployeeId>'".mysql_real_escape_string ($_REQUEST['code'])."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
And below is my manifest file: 以下是我的清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.david.Connect"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".ConnectActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
Can anyone shed some light on this? 任何人都可以对此有所了解吗? Its driving me nuts! 它让我疯了!
Thanks 谢谢
在浏览器上打开该页面(employee.php),查看源代码(大多数浏览器上的CTRL + U)并确保只返回一个JSON字符串,因为它在尝试将结果解析为JSON数组时明显失败。
If I visit http://86.47.59.249/employee.php in a browser, I get a 404 error. 如果我在浏览器中访问http://86.47.59.249/employee.php ,我会收到404错误。 This is because your PHP script is either not set up correctly, or not where you think it is. 这是因为您的PHP脚本要么设置不正确,要么设置不正确。
You need to do two things: 你需要做两件事:
In you Java, check the response code of the request. 在Java中,检查请求的响应代码。 You can do this like so: 你可以这样做:
// ...
HttpResponse response = httpclient.execute(httppost);
StatusLine responseStatus = response.getStatusLine();
if (responseStatus.getStatusCode() != 200) {
// Handle error here
} else {
HttpEntity entity = response.getEntity();
// ...
In your PHP, you need to handle potential errors: 在PHP中,您需要处理潜在的错误:
<?php
// Database connection settings
$dbHost = '86.47.59.249';
$dbUser = 'username';
$dbPass = 'password';
$dbName = 'Test';
// Try and connect to the database
if (!mysql_connect($dbHost, $dbUser, $dbPass)) {
header('HTTP/1.1 500 Internal Server Error');
exit('Oh No! Something went wrong connecting to the database: '.mysql_error());
} else if (!mysql_select_db($dbName)) {
header('HTTP/1.1 500 Internal Server Error');
exit('Oh No! Something went wrong selecting the database: '.mysql_error());
}
// Define SQL query
$query = "SELECT *
FROM Tbl_Employee
WHERE EmployeeId > '".mysql_real_escape_string($_REQUEST['code'])."'";
// Try and execute the query
if (!$result = mysql_query($query)) {
header('HTTP/1.1 500 Internal Server Error');
exit('Oh No! Something went wrong with the query: '.mysql_error());
}
// Fetch all results into an array
while ($row = mysql_fetch_assoc($result)) {
$output[] = $e;
}
// Close database link
// You can safely leave this line out, PHP implicitly does this when
// it terminates
mysql_close();
// Exit with a JSON encoded string of the results
exit(json_encode($output));
Use firefox with the firebug extension to see what data your php script is returning. 使用带有firebug扩展的firefox来查看php脚本返回的数据。 You most likely are not using the correct JSON.get* function. 您很可能没有使用正确的JSON.get *函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.