无法使用PHP从Android连接到MySQL

时间:2011-12-08 13:02:07

标签: php android mysql

我正在尝试通过以下教程从Android设备连接到MySQL:http://www.anddev.org/networking-database-problems-f29/connecting-to-mysql-database-t50063.html

所有发生的事情是它正在模拟器上打印我想要连接的服务器的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>

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

由于

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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));

答案 2 :(得分:0)

使用firefox和firebug扩展来查看php脚本返回的数据。您很可能没有使用正确的JSON.get *函数。