Android App端与PHP Web端的简单数据交互实现示例
2020年02月15日
作者:佚名
前言
由于学校科技立项的项目需要实现Android App端与PHP Web端的简单数据交互的实现,当前场景是Web端使用的是MySql数据库,Apache服务器和PHP语言编写的。数据交互的简单理解就是Android能向服务端进行数据获取,同时也能进行数据提交。
实现流程
JSON
{ "items": [ { "what": "手表","when": "2017-10-21 00:00:00","where": "北区宿舍楼#504","detail": "白色的手表,XX品牌","posttime": "2017-10-21 13:03:09","contact": "138123456" },{ "what": "手机","when": "2017-10-04 00:00:00","where": "北区商店#111","detail": "iphone6s,土豪金","posttime": "2017-10-21 13:03:46","contact": "137123456" },{ "what": "电脑","when": "2017-10-21 14:39:54","where": "图书馆#203","detail": "联想品牌笔记本","posttime": "2017-10-21 17:08:14","contact": "5670001" },{ "what": "细说PHP","when": "2017-09-21 13:03:46","where": "南馆#403","detail": "黑色封面,第二版《细说PHP》","posttime": "2017-10-21 17:36:53","contact": "63513641" } ],"success": 1 }
提交数据
create_found_items.php
<?php header('Content-Type:text/html;charset=utf-8');/*设置php编码为utf-8*/ /* * Following code will create a new product row * All product details are read from HTTP GET Request */ // array for JSON response $response = array(); // check for required fields if (isset($_GET['what']) && isset($_GET['when']) && isset($_GET['where']) && isset($_GET['detail'])&& isset($_GET['contact'])) { $what = $_GET['what']; $when = $_GET['when']; $where = $_GET['where']; $detail = $_GET['detail']; $contact = $_GET['contact']; // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $db = new DB_CONNECT(); // mysql inserting a new row $result2 = mysql_query("INSERT INTO guests(contact) VALUES('$contact')"); $gidresult = mysql_query("SELECT id FROM `guests` WHERE contact='$contact'"); while ($row = mysql_fetch_array($gidresult)) { $gid=$row['id']; } $result1 = mysql_query("INSERT INTO items(`what`,`when`,`where`,`type`,`gid`,`detail`) VALUES('$what','$when','$where','1','$gid','$detail')"); // check if row inserted or not if ($result1 && $result2) { // successfully inserted into database $response["success"] = 1; $response["message"] = "Items successfully created."; // echoing JSON response echo json_encode($response,JSON_UNESCAPED_UNICODE); } else { // failed to insert row $response["success"] = 0; $response["message"] = "Oops! An error occurred."; // echoing JSON response echo json_encode($response,JSON_UNESCAPED_UNICODE); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response,JSON_UNESCAPED_UNICODE); } ?>
判断GET请求的参数是否都存在,把获取的GET请求参数作为数据INSERT TO MySQL数据库。判断INSERT执行过程赋值$response[“success”]对应相应的$response[“message”],显示在Web页面。
执行结果
Andorid端
提交结果
结语
以上过程基本实现,项目基本上可以交差了。这个项目PHP部分主要是由自己在弄,也是边学边做。Android方面是另外一个同学主要负责,期间也求助过我实习时结交的朋友帮助。感谢所有付出与帮助的人。希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
以上是来客网为你收集整理的Android App端与PHP Web端的简单数据交互实现示例全部内容,希望文章能够帮你解决Android App端与PHP Web端的简单数据交互实现示例所遇到的程序开发问题。
如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。