1. 云栖社区>
  2. PHP教程>
  3. 正文

Android程序通过Apache服务器执行PHP程序连接Mysql数据库(重要!)

作者:用户 来源:互联网 时间:2017-12-01 11:30:36

数据库服务器程序

Android程序通过Apache服务器执行PHP程序连接Mysql数据库(重要!) - 摘要: 本文讲的是Android程序通过Apache服务器执行PHP程序连接Mysql数据库(重要!), Android程序通过Apache服务器执行PHP程序连接Mysql数据库(重要。),有需要的朋友可以参考下。 看了网上别人的文章弄了许久,总算成功了,提醒一下,android程序得导入包org.apache的jar包. db_confi

Android程序通过Apache服务器执行PHP程序连接Mysql数据库(重要。),有需要的朋友可以参考下。


看了网上别人的文章弄了许久,总算成功了,提醒一下,android程序得导入包org.apache的jar包.

db_config.php:

<?php/** * Created by PhpStorm. * User: Ollydebug * Date: 2015/11/17 * Time: 20:05 */define('DB_USER',"root");   //db userdefine('DB_PASSWORD',"");   //db passworddefine('DB_DATABASE',"test");   //database namedefine('DB_SERVER',"localhost");  //db server?>
server.php:

<?php/** * Created by PhpStorm. * User: Ollydebug * Date: 2015/11/17 * Time: 19:48 */include('db_config.php');$address = $_POST['address'];$longitude = $_POST['longitude'];$latitude = $_POST['latitude'];$id = $_POST['_id'];$tableName = "androidtable";if(empty($address)or empty($longitude)or empty($latitude)){    die("You have to fill all the fields!");}$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);if(!$conn){    die("connection failed:".mysql_error());}mysql_select_db(DB_DATABASE,$conn);$query = "insert into ".$tableName." values(".$id.",'".$address."',".$longitude.",".$latitude.",'".date('Y-m-d H:i:s',time())."');";$result = mysql_query($query,$conn);if(!$result){    die("mysql error:".mysql_error());}echo "add information to database sucessfullly!";?>

Android:

请求网络为耗时操作,必须操作在子线程当中.另外别忘了加权限.题主开头各种坑......

   <uses-permission android:name="android.permission.INTERNET" />


java:

(啰嗦一下,PHP文件得放到apache服务器的文件夹下,然后注意不能用localhost)

android访问服务器的时候不能用localhost或者127.0.0.1,因为android自己本身也有本地服务器,这样就找不到你的地址,

必须得用内网的ip地址,切记。。

package com.example.ollydebug.myapplication;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;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.apache.http.util.EntityUtils;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity {    private static final String TAG = "MainActivity";    private TextView tv = null;    private Button button = null;    @Override    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView)findViewById(R.id.outputTxt);button = (Button)findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {    System.out.println("-->开启子线程");    new TaskThread().start();}});    }    Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {    case 0:    {System.out.println("-->回到主线程刷新ui任务");String result = "add information to database sucessfullly!";tv.setText(result);Log.i(TAG,"result = "+result);    }    break;    default:break;}};    };    class TaskThread extends Thread {public void run() {System.out.println("-->做一些耗时的任务");String url = "http://172.19.82.99/AndroidInteraction/server.php";HttpPost httpRequest = new HttpPost(url);List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("_id","1"));params.add(new BasicNameValuePair("address", "yinchengzhi"));params.add(new BasicNameValuePair("longitude", "100.252255"));params.add(new BasicNameValuePair("latitude", "-15.415121"));try {    HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");    httpRequest.setEntity(httpEntity);    HttpClient httpClient = new DefaultHttpClient();    HttpResponse httpResponse = httpClient.execute(httpRequest);    if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){String result = EntityUtils.toString(httpResponse.getEntity());System.out.println(result);/*如果要更新视图不能在子线程中更新,只能在主线程中刷新UItv.setText(result);Log.i(TAG,"result = "+result);*/Message msg = new Message();msg.what = 0;handler.sendMessage(msg);    }else{tv.setText("request error");    }} catch (UnsupportedEncodingException e) {    // TODO Auto-generated catch block    e.printStackTrace();} catch (ClientProtocolException e) {    // TODO Auto-generated catch block    e.printStackTrace();} catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();}try {    sleep(500);} catch (InterruptedException e) {    e.printStackTrace();}handler.sendEmptyMessage(0);};    };}


xml:

(这个简单。不罗嗦了。)

<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true"    tools:context="com.example.ollydebug.myapplication.MainActivity">    <android.support.design.widget.AppBarLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:theme="@style/AppTheme.AppBarOverlay"><android.support.v7.widget.Toolbarandroid:id="@+id/toolbar"android:layout_width="match_parent"android:layout_height="?attr/actionBarSize"android:background="?attr/colorPrimary"app:popupTheme="@style/AppTheme.PopupOverlay" />    </android.support.design.widget.AppBarLayout>    <include layout="@layout/content_main" />    <android.support.design.widget.FloatingActionButtonandroid:id="@+id/fab"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="bottom|end"android:layout_margin="@dimen/fab_margin"android:src="@android:drawable/ic_dialog_email" /></android.support.design.widget.CoordinatorLayout>




版权声明:本文为博主原创文章,未经博主允许不得转载。

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索数据库 , 服务器 程序 ,以便于您获取更多的相关知识。