PHP และ JSON กับ Web Service การรับส่งข้อมูลจาก MySQL ในรูปแบบของ JSON |
Screenshot
ที่มาhttps://www.thaicreate.com/community/php-web-service-json.html

jQuery Ajax กับ JSON ทำความเข้าใจ การรับส่งข้อมูล JSON ผ่าน jQuery กับ Ajax
ก่อนอ่านบทความนี้ควรอ่าน 3 บทความนี้ก่อน
Go to : jQuery Ajax กับ JSON ทำความเข้าใจ การรับส่งข้อมูล JSON ผ่าน jQuery กับ Ajax
Go to : วิธีการสร้าง PHP กับ Web Service และ Return Array ไปยัง Client ด้วย NuSoap
Go to : PHP - Web Service กับ MySQL Database รับส่งค่า Result ผ่านเว็บเซอร์วิส (NuSoap)
Go to : วิธีการสร้าง PHP กับ Web Service และ Return Array ไปยัง Client ด้วย NuSoap
Go to : PHP - Web Service กับ MySQL Database รับส่งค่า Result ผ่านเว็บเซอร์วิส (NuSoap)
จากบทความก่อน ๆ เราจะใช้การรับส่งข้อมูลจาก Web Service ในรูปแบบของ String และ Array ซึ่งจะมีข้อกำกัดในกรณีที่ต้องการส่งข้อมูลในรูปแบบ Array ที่มีความซับซ้อน มี Key และ Value หลายตัว ทำได้ยากยิ่งขึ้น และการอ่านข้อมูลระหว่าง Server กับ Client ก็มีปัญหาในกรณีที่ Client ไม่สามารถรับค่า Array ได้โดยตรง เพราะฉะนั้นจึงเกิดมีการนำ JSON มาเป็นสื่อกลางในการรับส่งแลกเปลี่ยนข้อมูล
ฐานข้อมูลฝั่ง Server
01.CREATE TABLE `customer` (02.`CustomerID` varchar(4) NOT NULL,03.`Username` varchar(30) NOT NULL,04.`Password` varchar(30) NOT NULL,05.`Name` varchar(50) NOT NULL,06.`Email` varchar(50) NOT NULL,07.`CountryCode` varchar(2) NOT NULL,08.`Budget` double NOT NULL,09.`Used` double NOT NULL,10.PRIMARY KEY (`CustomerID`)11.) ENGINE=MyISAM DEFAULT CHARSET=utf8;12. 13.--14.-- Dumping data for table `customer`15.--16. 17.INSERT INTO `customer` VALUES ('C001', 'win', 'win001', 'Win Weerachai', 'win.weerachai@thaicreate.com', 'TH', 1000000, 600000);18.INSERT INTO `customer` VALUES ('C002', 'john', 'john002', 'John Smith', 'john.smith@thaicreate.com', 'EN', 2000000, 800000);19.INSERT INTO `customer` VALUES ('C003', 'jame', 'jame003', 'Jame Born', 'jame.born@thaicreate.com', 'US', 3000000, 600000);20.INSERT INTO `customer` VALUES ('C004', 'chalee', 'chalee004', 'Chalee Angel', 'chalee.angel@thaicreate.com', 'US', 4000000, 100000);นำคำสั่ง SQL นี้ไปสร้าง Database ในฝั่งของ Web Service Server

เมื่อสร้างเสร็จจะได้โครงสร้างและข้อมูลดังรูป

สำหรับบทความนี้ใช้ Library ของ NuSoap สามารถดาวน์โหลดได้ที่
หรือจะดาวน์โหลดได้จากในส่วนท้ายของบทความ
Code เต็ม ๆ
Web Service ฝั่ง Server
WebServiceServer.php
01.<?php02.require_once("lib/nusoap.php");03. 04.//Create a new soap server05.$server = new soap_server();06. 07.//Define our namespace08.$namespace = "http://localhost/nusoap/index.php";09.$server->wsdl->schemaTargetNamespace = $namespace;10. 11.//Configure our WSDL12.$server->configureWSDL("getCustomer");13. 14.// Register our method and argument parameters15.$varname = array(16.'strCountry' => "xsd:string"17.);18.$server->register('resultCustomer',$varname, array('return' => 'xsd:string'));19. 20.function resultCustomer($strCountry)21.{22.$objConnect = mysql_connect("localhost","root","") or die(mysql_error());23.$objDB = mysql_select_db("mydatabase");24.$strSQL = "SELECT * FROM customer WHERE 1 AND CountryCode like '%".$strCountry."%' ";25.$objQuery = mysql_query($strSQL) or die (mysql_error());26.$intNumField = mysql_num_fields($objQuery);27.$resultArray = array();28.while($obResult = mysql_fetch_array($objQuery))29.{30.$arrCol = array();31.for($i=0;$i<$intNumField;$i++)32.{33.$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];34.}35.array_push($resultArray,$arrCol);36.}37. 38.return json_encode($resultArray);39.}40. 41.// Get our posted data if the service is being consumed42.// otherwise leave this data blank.43.$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';44. 45.// pass our posted data (or nothing) to the soap service46.$server->service($POST_DATA);47.exit();48.?>คำอธิบาย
จาก Code ของ Web Service ในฝั่ง Server เมื่อมีการ result ข้อมูลจาก MySQL ลงใน Array ได้แล้ว จะมีการ return ข้อความผ่านการ encode ในรูปแบบ JSON ด้วย function ของ php ชื่อว่า json_encode()
มุมมองของ Array
01.array(2) {02.[0]=>03.object(stdClass)#4 (6) {04.["CustomerID"]=>05.string(4) "C003"06.["Name"]=>07.string(9) "Jame Born"08.["Email"]=>09.string(24) "jame.born@thaicreate.com"10.["CountryCode"]=>11.string(2) "US"12.["Budget"]=>13.string(7) "3000000"14.["Used"]=>15.string(6) "600000"16.}17.[1]=>18.object(stdClass)#5 (6) {19.["CustomerID"]=>20.string(4) "C004"21.["Name"]=>22.string(12) "Chalee Angel"23.["Email"]=>24.string(27) "chalee.angel@thaicreate.com"25.["CountryCode"]=>26.string(2) "US"27.["Budget"]=>28.string(7) "4000000"29.["Used"]=>30.string(6) "100000"31.}32.}มุมมองของ JSON
[
{"CustomerID":"C003","Name":"Jame Born","Email":"jame.born@thaicreate.com","CountryCode":"US","Budget":"3000000","Used":"600000"}
,{"CustomerID":"C004","Name":"Chalee Angel","Email":"chalee.angel@thaicreate.com","CountryCode":"US","Budget":"4000000","Used":"100000"}
]
{"CustomerID":"C003","Name":"Jame Born","Email":"jame.born@thaicreate.com","CountryCode":"US","Budget":"3000000","Used":"600000"}
,{"CustomerID":"C004","Name":"Chalee Angel","Email":"chalee.angel@thaicreate.com","CountryCode":"US","Budget":"4000000","Used":"100000"}
]
โดยสิ่งที่ Web Service ได้ return ค่ากลับไปก็เป็นค่าที่ถูกแปลง JSON เท่านั้น ซึ่งฝั่ง Client สามารถใช้ function ในการ decode รูปแบบ JSON ได้เช่นเดียวกัน
Web Service ฝั่ง Client ด้วย PHP
ทดสอบการเรียก Web Service ในรูปแบบฝั่ง Client ด้วย PHP แต่ถ้าหากต้องการรับส่งด้วย Array ก็สามารถอ่านได้ตามคำแนะนำจาก Link ข้างบน
WebServiceClient.php
01.<html>02.<head>03.<title>ThaiCreate.Com</title>04.</head>05.<body>06. 07.<form name="frmMain" method="post" action="">08.<h2>Search Customer</h2>09.Search by Country Code10.<input type="text" name="txtCountry" value="<?php echo $_POST["txtCountry"];?>">11.<input type="submit" name="Submit" value="Submit">12.</form>13. 14.<?php15.if($_POST["txtCountry"] != "")16.{17.include("lib/nusoap.php");18.$client = new nusoap_client("http://localhost/nusoap/WebServiceServer.php?wsdl",true);19.$params = array(20.'strCountry' => $_POST["txtCountry"]21.);22.$data = $client->call('resultCustomer', $params);23. 24.//echo '<pre>';25.//var_dump(json_decode($data));26.//echo '</pre><hr />';27. 28.$mydata = json_decode($data,true); // json decode from web service29. 30. 31.if(count($mydata) == 0)32.{33.echo "Not found data!";34.}35.else36.{37.?>38.<table width="500" border="1">39.<tr>40.<td>CustomerID</td>41.<td>Name</td>42.<td>Email</td>43.<td>CountryCode</td>44.<td>Budget</td>45.<td>Used</td>46.</tr>47.<?php48.foreach ($mydata as $result) {49.?>50.<tr>51.<td><?php echo $result["CustomerID"];?></td>52.<td><?php echo $result["Name"];?></td>53.<td><?php echo $result["Email"];?></td>54.<td><?php echo $result["CountryCode"];?></td>55.<td><?php echo $result["Budget"];?></td>56.<td><?php echo $result["Used"];?></td>57.</tr>58.<?php59.}60.}61. 62.}63.?>64.</body>65.</html>คำอธิบาย
จาก Code ฝั่งของ Client มีการส่งค่า Country เพื่อไปค้นหาข้อมูลใน Web Service ฝั่ง Server และฝั่ง Server จะส่งข้อมูลกลับมาในรูปแบบของ JSON ซึ่งเมื่อ Client ได้ค่า JSON กลับมาก็ใช้การ decode ด้วย function ของ php ที่ชื่อว่า json_decode() โดยเมื่อผ่านการ decode ตัวแปรที่ได้จะอยู่ในรูปแบบของ Array และสามารถใช้ loop foreach หรืออื่น ๆ เพื่อทำอ่านการค่าออกมา
Screenshot

ไม่มีความคิดเห็น:
แสดงความคิดเห็น