English 中文(简体)
使用 PHP 连接 Mysql 和机器人
原标题:connecting mysql from android using PHP

可能与包含以下代码的 php 文件有问题 :

    <?php
mysql_connect("localhost","root","");
mysql_select_db("deal");
$sql=mysql_query("select * from CITY");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

simple code to retrieve all cities in db. I located this file in: C:Program FilesEasyPHP-5.3.9wwwcity.php

Java 代码非常简单, 连接并显示查询结果:

package com.udios.mysql;

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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MySQLActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onTestClick(View view) {
        /*Toast.makeText(MySQLActivity.this, "Test Pressed", Toast.LENGTH_SHORT)
                .show();*/

        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                String result = null;

                JSONArray jArray;
                InputStream is = null;
                StringBuilder sb = null;
                try {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://127.0.0.1/city.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();

                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is, "iso-8859-1"), 8);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "
");

                    String line = "0";
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "
");
                    }
                    is.close();
                    result = sb.toString();

                    int ct_id;
                    String ct_name;
                    Toast.makeText(getBaseContext(), "result is: "+result,
                            100).show();
                    jArray = new JSONArray(result);
                    JSONObject json_data = null;
                    for (int i = 0; i < jArray.length(); i++) {
                        json_data = jArray.getJSONObject(i);
                        ct_id = json_data.getInt("CITY_ID");
                        ct_name = json_data.getString("CITY_NAME");


                        Toast.makeText(getBaseContext(), Integer.toString(ct_id)+" : " +  ct_name , 
                                Toast.LENGTH_LONG).show();

                    }
                } catch (JSONException e1) {
                    Toast.makeText(getBaseContext(), "No City Found",
                            Toast.LENGTH_LONG).show();
                } catch (ParseException e1) {
                    e1.printStackTrace();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

            }
        });

    }
}

当 i m 试图在浏览器中直接访问 :

I gets: Notice: Undefined variable: output in C:Program FilesEasyPHP-5.3.9wwwcity.php on line 7 null

i m 调试机和机器人,这条线排除了例外情况:(最后捕获)

HttpPost httppost = new HttpPost("http://127.0.0.1/city.php");

如果将其修改为10.0.2.2, 则在此行中排除例外 :

HttpResponse response = httpclient.execute(httppost);

i ve really tried all combination, Can someone please help me? thank you very much udi

最佳回答

您第一次在 $output 中添加一行, 这是未定义的 。

在您的 PHP 代码循环前添加此选项 。

$output = array();

如果您在模拟器上运行,或者您在真实设备上的本地 IP, 您也需要连接到 10.0. 2.2 (确保设备通过 WiFi 连接到您的网络) 。

问题回答

您的 HttpPost 正在试图连接它正在运行的电话。 它需要指向运行您的服务器的计算机 。 127.0.0.1 = 此 DEVICE 。





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签