查阅了很多资料,修改了别人的代码,终于实现了android向阿里云服务器的数据传输功能。以下说说自己的步骤:
1、软硬件环境
- Android Studio 3.2.2
- 阿里云服务器 ( Windows Sever 2012 )
- 软件集成包XAMPP(Apach、 MySql)
- 小米4
2、创建MySQL数据库 persondb 以及 表 persons
3、服务器端代码
a.先写个配置文件db_config.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', "root"); // db password (mention your db password here)
define('DB_DATABASE', "persondb"); // database name
define('DB_SERVER', "localhost"); // db server
?>
b.连接MySQL数据库的文件db_connect.php
<?php
function connect() {
/*包含并运行指定的文件*/
// import database connection variables
require_once __DIR__ . '/db_config.php';
global $con;
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_connect_error());
// Selecing database
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error($con)) ;
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
global $con;
mysqli_close($con);
}
?>
c. Android客户端从MySQL数据库里获取数据的文件get_all_persons.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
connect();
// get all products from products table
$result = mysqli_query($con,"SELECT *FROM persons") or die(mysqli_error());
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// products node
$response["persons"] = array();
while ($row = mysqli_fetch_array($result)) {
// temp user array
$info = array();
$info["Id_P"] = $row["Id_P"];
$info["LastName"] = $row["LastName"];
$info["FirstName"] = $row["FirstName"];
$info["Address"] = $row["Address"];
$info["City"] = $row["City"];
// push single product into final response array
array_push($response["persons"], $info);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
close();
?>
d.Android客户端向MySQL数据库插入数据的文件create_person.php