Android PHP MYSQL development simple example
I made an Android project some time ago, which required the use of a database. I have written a little about web pages before stuff, so I plan to use the golden partner of MYSQL PHP, although it is a bit overkill.
I am a real novice and don’t know much about Android. This project is purely to rush the ducks to the shelves. The reason why I write this blog is to share the experience I encountered in the project. I share the solutions to various problems with you, hoping it will be helpful to you.
Next, I will introduce how the Android client interacts with the MYSQL database through PHP from three aspects.
Overview
简单的说,安卓客户端通过Http向本地服务器发出请求,访问指定的php代码,服务器端通过php代码执行数据库的操作,
返回相应的JSON数据。服务器可以理解为运行着某些服务器容器的电脑,比如你的电脑安装了Apache并保持运行,那么电脑就变成了一台服务器,只是这台服务器没有入网,只能本地访问。安卓客户端通过HttpURLConnection向服务器中指定的php文件提交POST或GET请求,服务器端相应php代码接受来自客户端的参数(如果是带参传递)进行数据库的操作,返回JSON数据给客户端。
下面我以安卓客户端通过用户名密码登陆为例进行说明。具体为:客户端通过POST方法向服务器提交2个参数:用户名(username)和密码(password)到指定login.php文件(这个文件写登陆验证的php代码),该文件中通过查询数据库中是否存在该用户以及密码是否正确来返回客户端相应的JSON数据。
既然选择了PHP+MYSQL,那么使用wamp server套件是比较方便的一种选择,用过它的朋友都应该轻车熟路了。
1.Android client
安卓客户端所做的工作有:通过HttpURLConnection向服务器中指定的login.php文件提交POST或GET请求,服务器端接受来自客户端的参数执行login.php文件进行数据库的操作,返回JSON数据给客户端。
这里只贴出代码部分,至于界面只需要2个文本编辑框edittext用于输入用户名密码,一个button登陆按钮,其id自行设置即可。
登陆按钮响应函数如下
loginbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {//登陆按钮监听事件 /* ((App)getApplicationContext()).setTextData(et.getText().toString()); location_x.setText(((App)getApplicationContext()).getTextData());*/ new Thread(new Runnable() { @Override public void run() { try { int result = login(); //login()为向php服务器提交请求的函数,返回数据类型为int if (result == 1) { Log.e("log_tag", "登陆成功!"); //Toast toast=null; Looper.prepare(); Toast.makeText(PhpActivity.this, "登陆成功!", Toast.LENGTH_SHORT).show(); Looper.loop(); } else if (result == -2) { Log.e("log_tag", "密码错误!"); //Toast toast=null; Looper.prepare(); Toast.makeText(PhpActivity.this, "密码错误!", Toast.LENGTH_SHORT).show(); Looper.loop(); } else if (result == -1) { Log.e("log_tag", "不存在该用户!"); //Toast toast=null; Looper.prepare(); Toast.makeText(PhpActivity.this, "不存在该用户!", Toast.LENGTH_SHORT).show(); Looper.loop(); } } catch (IOException e) { System.out.println(e.getMessage()); } } }).start(); } });
登陆按钮响应函数中有个login()函数,这个函数就是完成向服务器提交申请并获取服务器返回json数据的功能。
/* *用户登录提交post请求 * 向服务器提交数据1.user_id用户名,2.input_pwd密码 * 返回JSON数据{"status":"1","info":"login success","sex":"0","nicename":""} */ private int login() throws IOException { int returnResult=0; /*获取用户名和密码*/ String user_id=et.getText().toString(); String input_pwd=pwd.getText().toString(); if(user_id==null||user_id.length()<=0){ Looper.prepare(); Toast.makeText(PhpActivity.this,"请输入账号", Toast.LENGTH_LONG).show(); Looper.loop(); return 0; } if(input_pwd==null||input_pwd.length()<=0){ Looper.prepare(); Toast.makeText(PhpActivity.this,"请输入密码", Toast.LENGTH_LONG).show(); Looper.loop(); return 0; } String urlstr="http://192.168.191.1/LBS/login.php"; //建立网络连接 URL url = new URL(urlstr); HttpURLConnection http= (HttpURLConnection) url.openConnection(); //往网页写入POST数据,和网页POST方法类似,参数间用‘&’连接 String params="uid="+user_id+'&'+"pwd="+input_pwd; http.setDoOutput(true); http.setRequestMethod("POST"); OutputStream out=http.getOutputStream(); out.write(params.getBytes());//post提交参数 out.flush(); out.close(); //读取网页返回的数据 BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(http.getInputStream()));//获得输入流 String line=""; StringBuilder sb=new StringBuilder();//建立输入缓冲区 while (null!=(line=bufferedReader.readLine())){//结束会读入一个null值 sb.append(line);//写缓冲区 } String result= sb.toString();//返回结果 try { /*获取服务器返回的JSON数据*/ JSONObject jsonObject= new JSONObject(result); returnResult=jsonObject.getInt("status");//获取JSON数据中status字段值 } catch (Exception e) { // TODO: handle exception Log.e("log_tag", "the Error parsing data "+e.toString()); } return returnResult; }
对于这个login()函数有几点说明:
1) urlstr="http://192.168.191.1/LBS/login.php"。其中192.168.191.1即本地电脑运行的Apache服务器的地址,这个地址会映射到Wamp安装目录下的WWW目录,LBS即为WWW目录下的文件夹。
一开始我使用android studio自带模拟器进行测试,网上说是浏览器访问10.0.2.0什么的就能访问电脑上的本地Apache服务器,但是没能成功访问wamp自带的apache服务器。
最后找到一个极好方法,就是使用真机测试,作为服务器的电脑需要安装一个wifi共享软件(如猎豹wifi),用要测试的真机连接该wifi后,手机浏览器访问http://192.168.191.1,如果显示
如下图则说明手机访问电脑apache服务器成功,至此服务器环境已经搭建成功。login.php是放在电脑的apache服务器下的,比如我的是在D:\wamp\www\LBS文件夹下。
2) HttpURLConnection。本人曾在网上找到过一些安卓网络请求的方法,但是大多都已弃用,使用HttpURLConnection是当前还未弃用的一种方法,当然对于高手来说,这就不值一提了。
2. Server side
3) JSONObject。
由于在后面的php代码中所返回的数据为json数据类型,所以需要在客户端进行解析,这并不困难,不清楚的可以搜索一下。
4)之前已经说过,本人对安卓一窍不通,所以在测试时犯了一个大忌,就是网络访问不能放在主线程中,否则会阻塞主线程,造成UI假死等错误,所以需要单开一个线程,即
登陆按钮响应函数中的run方法。
login.php在服务器容器中,时刻响应着外部的访问请求,主要工作是:
1)获取手机端通过Post请求发送的用户名密码。
where conn.php is the database connection file, the code is as follows
2)连接数据库,从数据库中查找是否有与该用户名密码一致的记录,根据查找结果返回不同的Json数据。
3.MYSQL database
As for the database, you can create it yourself. According to the above PHP code, there is a user in the database Table, there are 4 fields in the table, namely userid, password, nicename, and sex. You can create it by yourself (nicename and sex are not used in this example). The screenshot is as follows
##After the above work is completed, deploy the client to the real machine for testing
Enter the username and password, click the login button, the result is as follows:
What this article talks about is just the simplest example of combining php with Android , in fact, many large projects adopt this model, such as Sina Weibo client, etc. Interested readers can query relevant information and data, such as "Android PHPBest Practices" 》, once again, since I am also a rookie and have learned a lot from the blog posts of many seniors, I would like to share my learning experience with you here, so if there are any mistakes in the article, you are welcome to criticize. Correction.
Key source code
PS: When will CSDN release My own text editing tools are a bit easier to use.
This article explains a simple example of Android PHP MYSQL development. For more related content, please pay attention to the php Chinese website.Related recommendations:
Detailed explanation of the usage of $this in PHPThe relationship between Java and PHPSummary of practical experience with PHP
The above is the detailed content of Explanation of simple examples of Android+PHP+MYSQL development. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft