2021年1月7日 星期四

Ubuntu 20.04+PHP -資料存取(五) POST+JSON+MaraiaDB

 


參考來源:

 Connecting iOS App to MySQL Database with Swift 5 Using Protocol Delegation and MVC Architectural Pattern

  https://medium.com/@joseortizcosta/connecting-ios-app-to-mysql-database-with-swift-5-using-protocol-delegation-and-mvc-architectural-259dc32fcc4b

 Swift: Uploading Data Securely to a MySQL Database 

  https://www.boomer.org/ios/sdb/

 The Best Way to Connect Your iOS App to MySQL Database (4 Steps)  

  https://codewithchris.com/iphone-app-connect-to-mysql-database/

 利用 Postman 來測試 Web Service 的工具

  https://franksios.medium.com/postman-測試web-service的工具-c7726997868a#.45rlrqve9

 Formatting JSON Data for Postman 

  https://stackoverflow.com/questions/38574039/formatting-json-data-for-postman


----------------------------------

建立檔案名稱: config.php 

並儲存到  https://www.mydomain.com/htdocs/config.php


 <?php

define('DB_USERNAME', 'root');

define('DB_PASSWORD', 'rootpasseprd');

define('DB_HOST', '192.168.1.X');

define('DB_NAME', 'mydbname');

?>

----------------------------------

開啟

 https://www.mydomain.com/phpmyadmin

建立一個資料庫, 名稱為  mydbname

-- Database : `mydbname`

CREATE DATABASE IF NOT EXISTS `mydbname`

  DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;

USE mydbname;

-- Privileges

GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `mydbname`.* TO

    'root'@localhost;


在資料庫mydbname 中建立一個TABLE, 名稱為  mytabelname 

在TABLE mytabelname 中建立 5個欄位

-- Table structure for table `mytabelname`

CREATE TABLE IF NOT EXISTS `mytabelname` (

  `id` int(5) unsigned NOT NULL auto_increment,

  `item1` varchar(20) NOT NULL default '',

  `item2` varchar(20) NOT NULL default '',

  `item3` varchar(20) NOT NULL default '',

  `item4` int(10) unsigned NOT NULL,  

  PRIMARY KEY  (`id`),

)

 COMMENT='mytabelname Test'

 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;

 

----------------------------------

建立檔案名稱: t5.php 

並儲存到  https://www.mydomain.com/htdocs/t5.php


<?php

   $response = array();

//   $jsondata = json_decode(file_get_contents('php://input'), true);

   $postdata = file_get_contents("php://input", 'r');

  var_dump($postdata); 

   $jsondata = json_decode($postdata, true);

  var_dump($jsondata); 

   $item1 = $jsondata["item1"];

   $item2 = $jsondata["item2"];

   $item3 = $jsondata["item3"];

   $item4 = $jsondata["item4"];


   require_once ("config.php");

   $conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

   if( !$conn) 

   {

    die("Connection failed: " . mysqli_connect_error());

   }

   else

   {

    $sql = "INSERT INTO mytabelname (name1, name2, name3, member) value ('$item1','$item2','$item3','$item4')";

    if (mysqli_query($conn, $sql)) 

    {

     $response['error']=false;

     $response['message']='mytabelname added successfully';

    }

    else 

    {

     echo "Error: " . $sql . "<br>" . mysqli_error($conn);

    }

    mysqli_close($conn);            

  }

  echo json_encode($response);

?>

----------------------------------

建立檔案名稱: t5.swift

iOS XCode 12.3 

import Foundation

import UIKit

func PhpJsonTest()

{

 // created NSURL

  let urlString = URL(string: "https://www.mydomain.com/htdocs/t5.php")!

  var request = URLRequest(url: urlString)

 // setting the method to post

  request.httpMethod = "POST"

 // creating the post parameter by concatenating the keys and values from text field

 let json: [String: Any] = ["item1": "ABC",

                            "item2": "DEF",

                            "item3": "HIJ",

                            "item4": "567"]

 let jsonData = try? JSONSerialization.data(withJSONObject: json)

 // insert json data to the request

 request.httpBody = jsonData

 // creating a task to send the post request

 let task = URLSession.shared.dataTask(with: request)

 {

  data, response, error in

   guard let data = data, error == nil else {

    DPrint(error?.localizedDescription ?? "No data")

     return

   }

  // parsing the response

  do

  {

   let responseJSON = try JSONSerialization.jsonObject(with: data, options: [])

   if let responseJSON = responseJSON as? [String: Any]

   {

    DPrint(responseJSON)

    var msg : String!

    // getting the json response

    msg = responseJSON["message"] as! String?

    DPrint("\(#file), \(#function), \(String(describing: msg))")

   }

  }

  catch

  {

   DPrint(error)

  }

 }

 //executing the task

 task.resume()

}

----------------------------------

開啟 Postman 測試

. 選擇 POST

  輸入網址 https://www.mydomain.com/htdocs/t5.php

  Body 選擇 raw 和 JSON

  傳送資料填入下列

{

  "item1": "ABC",

  "item2": "DEF",

  "item3": "XYO",

  "item4": "356"

}

. 點選 Send

. 結果

  $postdata = file_get_contents("php://input", 'r');

  $jsondata = json_decode($postdata, true);

  $item1 = $jsondata["item1"];    

  使用上面三行 就可以取得傳入之資料  





沒有留言:

張貼留言