Thứ Hai, 7 tháng 10, 2013

Android: Kết nối với MySQL theo mô hình Client-Server – Phần 1

[Giới thiệu]

Chúng ta sẽ cùng thực hiện một ứng dụng Android đơn giản (Quản lý sản phẩm) đơn giản, ứng dụng này sẽ gọi một đoạn PHP (có chức năng như một webservice) để thực hiện các tác vụ Tạo, Thêm, Đọc, Xoá, Sửa (CRUD) cơ sở dữ liệu MySQL.

Updated:
Luồng xử lý chung (Truyền dữ liệu từ MySQL về Android):
1. Android gọi PHP cùng yêu cầu thao tác + tham số
2. PHP kết nối MySQL và thực hiện tác vụ với tham số truyền vào + nhận kết quả trả về
3. PHP gửi trả chuỗi JSON kết quả về cho Android
4. Android decode chuỗi JSON để nhận dữ liệu.

Video quy trình thực hiện:


Lưu ý: Các hướng dẫn sau đây chỉ mang tính chất tham khảo trong học tập, nghiên cứu, trình diễn khả năng kết nối Android với PHP và MySQL. Nếu các bạn muốn áp dụng vào các sản phẩm thực tế thì cần phải chỉnh sửa lại theo các quy chuẩn nghiệp vụ (chẳng hạn như tránh SQL Injection, performance, security,…)

[Phần 1: Thiết lập Web server, MySQL và các PHP Webservices]

1. Web server (WAMP hoặc XAMPP)

Trong môi trường phát triển, ta thường sử dụng các máy chủ localhost để thí nghiệm và vận hành thử. Để cho đơn giản, ta sẽ sử dụng các gói máy chủ ảo WAMP hoặc XAMPP.
Các gói này bao gồm máy chủ PHP (Apache), MySQL và một số thành phần khác cần thiết cho một máy chủ (như FTP Server).

2. Cài đặt XAMPP

Trong bài này mình sẽ sử dụng XAMPP cho đơn giản và cross-platform (WAMP chỉ dành cho Windows, trong khi XAMPP có thể dùng cho cả Windows, Linux và Mac)
- Tải về XAMPP: http://www.apachefriends.org/en/xampp.html (chọn bản cài đặt cho phù hợp với HĐH đang sử dụng, ta chọn Windows)
- Cài đặt:
+ Giải nén, nên chọn C:\xampp hoặc X:\xampp, X là ổ đĩa không là ổ hệ thống)
+ Chạy file setup_xampp.bat, cứ chọn Yes cho các câu hỏi trong quá trình cài đặt.
- Khởi động server
+ Chạy file xampp-control.exe, trong hộp thoại hiện ra, ta đánh dấu và các mục trên hình và nhấn Start để khởi động Apache và MySQL

image

+ Test: Vào trình duyệt, gõ http://localhost Nếu hiện trang có dòng It’s work thì server đã setup thành công.

3. Tạo cơ sở dữ liệu trên MySQL

Ta sẽ tiến hành tạo CSDL với script:

CREATE DATABASE androidhive;

CREATE TABLE products(
    pid int(11) primary key auto_increment,
    name varchar(100) not null,
    price decimal(10,2) not null,
    description text,
    created_at timestamp default now(),
    updated_at timestamp
);

- Vào trình duyệt gõ địa chỉ http://localhost/phpmyadmin

- Ta sẽ sử dụng giao diện PHPMyAdmin để thao tác với MySQL. Các bạn có thể tham khảo video bên dưới.


4. Tạo PHP Webservice


- Thiết lập kết nối đến MySQL

Ta sẽ tạo 2 file: db_config.phpdb_connect.php để lưu các tham số kết nối và tạo kết nối.

db_config.php



db_connect.php

connect();
        }
     
        // destructor
        function __destruct() {
            // closing db connection
            $this->close();
        }
     
        /**
         * Function to connect with database
         */
        function connect() {
            // import database connection variables
            require_once __DIR__ . '/db_config.php';
     
            // Connecting to mysql database
            $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
     
            // Selecing database
            $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
     
            // returing connection cursor
            return $con;
        }
     
        /**
         * Function to close db connection
         */
        function close() {
            // closing db connection
            mysql_close();
        }
     
    }
 
?>


   1: <?php
   2:  
   3:     /**
   4:      * A class file to connect to database
   5:      */ 
   6:     class DB_CONNECT {
   7:      
   8:         // constructor
   9:         function __construct() {
  10:             // connecting to database
  11:             $this->connect();
  12:         }
  13:      
  14:         // destructor
  15:         function __destruct() {
  16:             // closing db connection
  17:             $this->close();
  18:         }
  19:      
  20:         /**
  21:          * Function to connect with database
  22:          */
  23:         function connect() {
  24:             // import database connection variables
  25:             require_once __DIR__ . '/db_config.php';
  26:      
  27:             // Connecting to mysql database
  28:             $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
  29:      
  30:             // Selecing database
  31:             $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

  32:      
  33:             // returing connection cursor
  34:             return $con;
  35:         }
  36:      
  37:         /**
  38:          * Function to close db connection
  39:          */
  40:         function close() {
  41:             // closing db connection
  42:             mysql_close();
  43:         }
  44:      
  45:     }
  46:  
  47: ?>

Khi cần kết nối đến MySQL ta sử dụng câu lệnh:

$db = new DB_CONNECT(); // creating class object(will open database connection)

5. Tạo các tác vụ CRUD (Create, Read/Retrieve, Update, Delete)


Ta sẽ làm việc với chuỗi JSON (khi trả kết quả về cho client)

Tạo mới một sản phẩm

Ta dùng $_POST để lấy tham số truyền vào (name, price, description) từ client là app Android, kết nối MySQL để chạy script. Sau đó ta trả về đoạn JSON thông báo kết quả về cho client.

Đoạn JSON có cấu trúc sau:

{
    "success": 0,
    "message": "Required field(s) is missing"
}
 

{
    "success": 1,
    "message": "Product successfully created."
}
 

{
    "success": 0,
    "message": "Oops! An error occurred."
} 

create_product.php


   1: <?php
   2:  
   3:     /*
   4:      * Following code will create a new product row
   5:      * All product details are read from HTTP Post Request
   6:      */
   7:      
   8:     // array for JSON response
   9:     $response = array();
  10:      
  11:     // check for required fields
  12:     if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
  13:      
  14:         $name = $_POST['name'];
  15:         $price = $_POST['price'];
  16:         $description = $_POST['description'];
  17:      
  18:         // include db connect class
  19:         require_once __DIR__ . '/db_connect.php';
  20:      
  21:         // connecting to db
  22:         $db = new DB_CONNECT();
  23:      
  24:         // mysql inserting a new row
  25:         $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
  26:      
  27:         // check if row inserted or not
  28:         if ($result) {
  29:             // successfully inserted into database
  30:             $response["success"] = 1;
  31:             $response["message"] = "Product successfully created.";
  32:      
  33:             // echoing JSON response
  34:             echo json_encode($response);
  35:         } else {
  36:             // failed to insert row
  37:             $response["success"] = 0;
  38:             $response["message"] = "Oops! An error occurred.";
  39:      
  40:             // echoing JSON response
  41:             echo json_encode($response);
  42:         }
  43:     } else {
  44:         // required field is missing
  45:         $response["success"] = 0;
  46:         $response["message"] = "Required field(s) is missing";
  47:      
  48:         // echoing JSON response
  49:         echo json_encode($response);
  50:     }
  51: ?>

Lấy một sản phẩm


get_product_details.php


   1: <?php
   2:  
   3:     /*
   4:      * Following code will get single product details
   5:      * A product is identified by product id (pid)
   6:      */
   7:      
   8:     // array for JSON response
   9:     $response = array();
  10:      
  11:     // include db connect class
  12:     require_once __DIR__ . '/db_connect.php';
  13:      
  14:     // connecting to db
  15:     $db = new DB_CONNECT();
  16:      
  17:     // check for post data
  18:     if (isset($_GET["pid"])) {
  19:         $pid = $_GET['pid'];
  20:      
  21:         // get a product from products table
  22:         $result = mysql_query("SELECT *FROM products WHERE pid = $pid");
  23:      
  24:         if (!empty($result)) {
  25:             // check for empty result
  26:             if (mysql_num_rows($result) > 0) {
  27:      
  28:                 $result = mysql_fetch_array($result);
  29:      
  30:                 $product = array();
  31:                 $product["pid"] = $result["pid"];
  32:                 $product["name"] = $result["name"];
  33:                 $product["price"] = $result["price"];
  34:                 $product["description"] = $result["description"];
  35:                 $product["created_at"] = $result["created_at"];
  36:                 $product["updated_at"] = $result["updated_at"];
  37:                 // success
  38:                 $response["success"] = 1;
  39:      
  40:                 // user node
  41:                 $response["product"] = array();
  42:      
  43:                 array_push($response["product"], $product);
  44:      
  45:                 // echoing JSON response
  46:                 echo json_encode($response);
  47:             } else {
  48:                 // no product found
  49:                 $response["success"] = 0;
  50:                 $response["message"] = "No product found";
  51:      

  52:                 // echo no users JSON
  53:                 echo json_encode($response);
  54:             }
  55:         } else {
  56:             // no product found
  57:             $response["success"] = 0;
  58:             $response["message"] = "No product found";
  59:      
  60:             // echo no users JSON
  61:             echo json_encode($response);
  62:         }
  63:     } else {
  64:         // required field is missing
  65:         $response["success"] = 0;
  66:         $response["message"] = "Required field(s) is missing";
  67:      
  68:         // echoing JSON response
  69:         echo json_encode($response);
  70:     }
  71: ?>


Tham số truyền vào là pid (mã sản phẩm)

Đoạn JSON trả về

{
    "success": 1,
    "product": [
        {
            "pid": "1",
            "name": "iPHone 4S",
            "price": "300.00",
            "description": "iPhone 4S white",
            "created_at": "2012-04-29 01:41:42",
            "updated_at": "0000-00-00 00:00:00"
        }
    ]
} 

{
    "success": 0,
    "message": "No product found"
}


Lấy tất cả sản phẩm

get_all_products.php
   1: <?php
   2:
   3:     /* 
   4:      * Following code will list all the products
   5:      */
   6:      
   7:     // array for JSON response
   8:     $response = array();
   9:      
  10:     // include db connect class
  11:     require_once __DIR__ . '/db_connect.php';
  12:       
  13:     // connecting to db
  14:     $db = new DB_CONNECT();
  15:      
  16:     // get all products from products table
  17:     $result = mysql_query("SELECT *FROM products") or die(mysql_error());
  18:      
  19:     // check for empty result
  20:     if (mysql_num_rows($result) > 0) {
  21:         // looping through all results
  22:         // products node
  23:         $response["products"] = array(); 
  24:      
  25:         while ($row = mysql_fetch_array($result)) {
  26:             // temp user array
  27:             $product = array();
  28:             $product["pid"] = $row["pid"];
  29:             $product["name"] = $row["name"];
  30:             $product["price"] = $row["price"];
  31:             $product["created_at"] = $row["created_at"];
  32:             $product["updated_at"] = $row["updated_at"];
  33:      
  34:             // push single product into final response array
  35:             array_push($response["products"], $product);
  36:         }
  37:         // success
  38:         $response["success"] = 1;
  39:      
  40:         // echoing JSON response
  41:         echo json_encode($response);
  42:     } else {
  43:         // no products found
  44:         $response["success"] = 0;
  45:         $response["message"] = "No products found";
  46:      
  47:         // echo no users JSON
  48:         echo json_encode($response);
  49:     }
  50: ?>

Đoạn JSON trả về

{
    "products": [
        {
            "pid": "1",
            "name": "iPhone 4S",
            "price": "300.00",
            "created_at": "2012-04-29 02:04:02",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "2",
            "name": "Macbook Pro",
            "price": "600.00",
            "created_at": "2012-04-29 02:04:51",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "3",
            "name": "Macbook Air",
            "price": "800.00",
            "created_at": "2012-04-29 02:05:57",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "4",
            "name": "OS X Lion",
            "price": "100.00",
            "created_at": "2012-04-29 02:07:14",
            "updated_at": "0000-00-00 00:00:00"
        }
    ],
    "success": 1
}

{
    "success": 0,
    "message": "No products found"
} 

Cập nhật sản phẩm


update_product.php

Tham số truyền vào: pid, name, price, description

   1: <?php
   2:      
   3:     /*
   4:      * Following code will update a product information
   5:      * A product is identified by product id (pid)
   6:      */
   7:      
   8:     // array for JSON response
   9:     $response = array();
  10:      
  11:     // check for required fields
  12:     if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
  13:      
  14:         $pid = $_POST['pid'];
  15:         $name = $_POST['name'];
  16:         $price = $_POST['price'];
  17:         $description = $_POST['description'];
  18:      
  19:         // include db connect class
  20:         require_once __DIR__ . '/db_connect.php';
  21:      
  22:         // connecting to db
  23:         $db = new DB_CONNECT();
  24:      
  25:         // mysql update row with matched pid
  26:         $result = mysql_query("UPDATE products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid");
  27:      
  28:         // check if row inserted or not
  29:         if ($result) {
  30:             // successfully updated
  31:             $response["success"] = 1;
  32:             $response["message"] = "Product successfully updated.";
  33:      
  34:             // echoing JSON response
  35:             echo json_encode($response);
  36:         } else {
  37:      
  38:         }
  39:     } else {
  40:         // required field is missing
  41:         $response["success"] = 0;
  42:         $response["message"] = "Required field(s) is missing";
  43:      
  44:         // echoing JSON response
  45:         echo json_encode($response);
  46:     }
  47: ?>
Đoạn JSON trả về

{
    "success": 1,
    "message": "Product successfully updated."
}

Xoá một sản phẩm

delete_product.php

   1: <?php
   2:      
   3:     /*
   4:      * Following code will delete a product from table
   5:      * A product is identified by product id (pid)
   6:      */
   7:      
   8:     // array for JSON response
   9:     $response = array();
  10:      
  11:     // check for required fields
  12:     if (isset($_POST['pid'])) {
  13:         $pid = $_POST['pid'];
  14:      
  15:         // include db connect class
  16:         require_once __DIR__ . '/db_connect.php';
  17:      
  18:         // connecting to db
  19:         $db = new DB_CONNECT();
  20:      
  21:         // mysql update row with matched pid
  22:         $result = mysql_query("DELETE FROM products WHERE pid = $pid");
  23:      
  24:         // check if row deleted or not
  25:         if (mysql_affected_rows() > 0) {
  26:             // successfully updated
  27:             $response["success"] = 1;
  28:             $response["message"] = "Product successfully deleted";
  29:      
  30:             // echoing JSON response
  31:             echo json_encode($response);
  32:         } else {
  33:             // no product found
  34:             $response["success"] = 0;
  35:             $response["message"] = "No product found";
  36:      
  37:             // echo no users JSON
  38:             echo json_encode($response);
  39:         }
  40:     } else {
  41:         // required field is missing
  42:         $response["success"] = 0;
  43:         $response["message"] = "Required field(s) is missing";
  44:      
  45:         // echoing JSON response
  46:         echo json_encode($response);
  47:     }
  48:  ?>

Đoạn JSON trả về

{
    "success": 1,
    "message": "Product successfully deleted"
}
 
{
    "success": 0,
    "message": "No product found"
}

Thẻ Technorati: ,,,,,

Còn tiếp…





3 nhận xét:

  1. hiu hiu, đại ka ơi, cho em xin cái mail, em hỏi bài với, e mới nhận cái đề tài thực tập tốt nghiệp mờ nó khoai ơi là khoai huhu

    Trả lờiXóa
  2. @CÔNG NGHÊ PHẦN MÊM

    Email của tớ: kevin.nguyenhoang91@gmail.com

    Trả lờiXóa
  3. a ơi phần 2 sắp được đăng chưa ?

    Trả lờiXóa