簡體   English   中英

無法使用PHP從Android連接到MySQL

[英]Unable to connect to MySQL from Android using PHP

我正在嘗試通過以下教程從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>

任何人都可以對此有所了解嗎? 它讓我瘋了!

謝謝

在瀏覽器上打開該頁面(employee.php),查看源代碼(大多數瀏覽器上的CTRL + U)並確保只返回一個JSON字符串,因為它在嘗試將結果解析為JSON數組時明顯失敗。

如果我在瀏覽器中訪問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));

使用帶有firebug擴展的firefox來查看php腳本返回的數據。 您很可能沒有使用正確的JSON.get *函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM