简体   繁体   English

无法使用php将android应用与mysql DB连接

[英]Unable to connect android app with mysql DB using php

The following is my code which connects android app with MySQL DB. 以下是我的代码,该代码将android应用程序与MySQL DB连接。 When I run this in my android mobile it just displays a plain screen. 当我在android手机中运行此程序时,它只会显示一个纯屏幕。 There is no error in my logcat. 我的logcat中没有错误。 When i run it in brower using "192.168.1.11/city.php" I am getting the city's extracted from DB. 当我使用"192.168.1.11/city.php"在浏览器中运行它时,我从DB中提取了该城市。 But the same is not working when I run it in my android device. 但是当我在android设备中运行它时,同样的方法不起作用。 Please help 请帮忙

Android class : Android类:

 public class City extends ListActivity {

     JSONArray jArray;
     String result = null;
     InputStream is = null;
     StringBuilder sb=null;

     @Override
     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     //http post
     try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.11/city.php");
        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);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");

        String line="0";
        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());
    }
   //paring data
   int ct_id;
   String ct_name;
   try{
  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");
     }
  }
  catch(JSONException e1){
      Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show();
  } catch (ParseException e1) {
        e1.printStackTrace();
}
   }
    }
}

activity_city.xml code : activity_city.xml代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".City" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

Php Code : 邮递区号:

 <?php
 ob_start();
 $host="localhost"; // Host name 
 $username=""; // Mysql username 
 $password=""; // Mysql password 
 $db_name="test"; // Database name 
 $tbl_name="CITY"; // Table name 
 mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
 mysql_select_db("$db_name")or die("cannot select DB");
 $sql=mysql_query("select * from CITY");
 while($row=mysql_fetch_assoc($sql))
{
$output[]=$row;
print(json_encode($output));
}
mysql_close();
?>

Included INTERNET permission in my Android Manifest file. 我的Android清单文件中包含INTERNET权限。

I dont know where I am going wrong. 我不知道我要去哪里错了。 Please help. 请帮忙。

Make sure you have your phone in same network as server. 确保您的电话与服务器位于同一网络中。

Try moving 尝试移动

print(json_encode($output)); print(json_encode($ output));

out of the loop 跳出循环

your PHP code need to be change.. So i have change it and put it back.. 您的PHP代码需要更改..因此,我将其更改并放回原处。

<?php
     ob_start();
     $host="localhost"; // Host name              Changed
     $username="root"; // Mysql username          Changed
     $password=""; // Mysql password 
     $db_name="test"; // Database name 

     $tbl_name="CITY"; // Table name 
     mysql_connect($host, $username, $password)or die("cannot connect");          //Changed
     mysql_select_db($db_name)or die("cannot select DB");           //Changed
     $sql=mysql_query("select * from CITY");
     while($row=mysql_fetch_assoc($sql))
     {
          $output[]=$row;
          print(json_encode($output));
     }
     mysql_close();
?>

Where is the PHP files located. PHP文件在哪里。 In a local machine , or on a web server. 在本地计算机上,或在Web服务器上。

If the PHP files are located in local machine, you can't access it from the android application. 如果PHP文件位于本地计算机上,则无法从android应用程序访问它。

Also verify that you have given internet permission for the android application. 还要确认您已为android应用程序授予了互联网权限。

Don't use localhost when you want to test your application on your phone. 如果要在手机上测试应用程序,请不要使用localhost。 Your phone can't access the PHP files on localhost. 您的电话无法访问localhost上的PHP文件。

Might I suggest hosting your PHP and SQL files online and resume testing. 可能我建议在线托管您的PHP和SQL文件并继续测试。

1) Are you sure ur localhost ip is " http://192.168.1.11 " ? 1)您确定您的本地主机IP是“ http://192.168.1.11 ”吗? try to put two / like this " http://192.168.1.11//city.php " 尝试把两个/这样的“ http://192.168.1.11//city.php

i have used this IP for my xampp " http://10.0.2.2//Mobile/login2.php " or try this as well 127.0.1.1 or 127.0.0.1 我已经将此IP用于我的xampp“ http://10.0.2.2//Mobile/login2.php ”,或者也尝试使用127.0.1.1或127.0.0.1

2) try this link . 2)试试这个链接 if you have done something wrong in java or php code than this will help you. 如果您在Java或php代码中做错了什么,那将对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM