Android向服务器的数据库MySQL传输数据:经过修正的 Android + HTTP + xampp +mysql : Post / Get

本文详细介绍了使用Android Studio、阿里云服务器和XAMPP环境,实现Android客户端向MySQL数据库进行POST和GET操作的过程。包括创建数据库、编写PHP服务器端代码、设置Android客户端布局和代码,最终实现数据的增删查改功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

查阅了很多资料,修改了别人的代码,终于实现了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


                
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值