2011-12-08 113 views
0

我想通过以下教程连接到Android设备的MySQL:http://www.anddev.org/networking-database-problems-f29/connecting-to-mysql-database-t50063.html无法使用PHP连接到MySQL从Android使用PHP

所有这一切发生的是,它正在打印我希望连接到模拟器上的服务器的IP地址。它显示了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 

下面是我的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; 
    } 

    } 

,这里是我的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(); 
    ?> 

而下面是我的清单文件:

<?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> 

任何人都可以对此有所了解吗?它让我疯狂!

感谢

+0

您应该紧急更改您的php脚本 - 将'$ _REQUEST ['code']'更改为'mysql_real_escape_string($ _REQUEST ['code'])''。如果没有这种改变,任何阅读这篇文章的人都会有足够的信息来轻易地破坏你的数据库,并且可能会使用SQL注入攻击你的服务器看到这个页面的背景阅读:http://php.net/manual/en/security.database.sql-injection.php –

+1

谢谢你只是改变那里 – DMC

回答

1

如果我在浏览器中访问http://86.47.59.249/employee.php,我得到一个404错误。这是因为你的PHP脚本要么设置不正确,要么没有正确设置。

你需要做两件事情:

在你的Java,检查请求的响应代码。你可以这样做,像这样:

// ... 
HttpResponse response = httpclient.execute(httppost); 
StatusLine responseStatus = response.getStatusLine(); 
if (responseStatus.getStatusCode() != 200) { 
    // Handle error here 
} else { 
    HttpEntity entity = response.getEntity(); 
    // ... 

在你的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)); 
+0

当你输入http://86.47.59.249/employee.php你不能访问它的原因是因为这不是我使用的实际地址。但是,当我输入实际地址时,我得到一个404错误,但是如果我使用http://的ftp:// intead输入地址,则可以连接。有什么方法将ftp合并到我的php文件中? – DMC

+0

@davemc FTP服务器不会调用(运行)PHP脚本并给出输出,它只会给你PHP源代码。您需要让PHP脚本在您的Web服务器上运行。如果它是一个有效的Web服务器,我想这可能只是将脚本移动到正确的目录以允许它作为网页服务的问题。 – DaveRandom

+0

好吧,我刚刚发现我连接到了错误的服务器。事实证明,我的电脑是托管MySQLServer的电脑。林有点困惑现在因为我不认为这是一个网络服务器。当我运行localhost \ employee.php它只是给了我打开或保存文件的选项。有任何想法吗? – DMC

1

在浏览器中打开该页面(employee.php),请查看源代码(CTRL + U大多数浏览器),并确保只返回一个JSON字符串,因为它清楚地在失败试图将结果解析为JSON数组。

0

使用Firefox的Firebug扩展,看看数据你的PHP脚本返回。你很可能没有使用正确的JSON.get *函数。