php - 无法使用 PHP 从 Android 连接到 MySQL

标签 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;
    }   

    }

这是我在服务器 86.47.59.29 上的 php 文件,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();
    ?>

下面是我的 list 文件:

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

有人能解释一下吗?这让我发疯!

谢谢

最佳答案

如果我访问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));

关于php - 无法使用 PHP 从 Android 连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8431394/

相关文章:

java - 无法使用crontab在mysql数据库中插入utf-8字符来自动化程序

php - 忽略重复记录但将它们置顶

php - 调用具有多个变量的函数

android - 我们可以限制android应用键盘使用其他语言而不是英语吗?

android - 如何在android中停止这个线程?

php - 删除所有行后出现消息错误(codeigniter)

php - mysql查询日志中的^M字符,它是从哪里来的?

php - jquery限制输入范围

java - 可以利用 Android API 在通话过程中修改调用者的声音吗?

php - 提高代码的效率和速度?