ASP.NET เรียก PHP กับฐานข้อมูล MySQL ผ่าน Web Service และการรับส่งค่าผ่านเว็บเซอร์วิส |
|
|
|
ASP.NET เรียก PHP กับฐานข้อมูล MySQL ผ่าน Web Service และการรับส่งค่าผ่านเว็บเซอร์วิส บทความนี้จะใช้ Web Service ที่เป็น PHP กับ MySQL โดยอ้างอิงจากบทความ การทำ Login Form และ Update MySQL Data ผ่าน Web Service ด้วย PHP (NuSoap) แต่จะใช้ ASP.NET ในการเรียก Web Service ของ PHP เช่น การตรวจสอบ Login , ข้อมูล และการแก้ไข Update ข้อมูลที่อยู่บน Web Service ของ PHP
Screenshot

หน้าจอเรียก Web Service ในการตรวจสอบการ Login ในหน้า Webpage ของ ASP.NET

หน้าจอสำหรับเรียกข้อมูลมาแสดงในหน้า Webpage ของ ASP.NET

หน้าจอแก้ไขข้อมูลบนหน้า Webpage ของ ASP.NET และข้อมูลจะถูกส่งไปอัพเดดที่ Web Service ฝั่ง Server
คำอธิบายเพิ่มเติม

สำหรับตัวอย่างนี้จะยกตัวอย่างเกี่ยวกับข้อมูลในตาราง MySQL ชื่อว่า customer ซึ่งจัดเก็บ CustomerID, Username, Password, Email, CountryCode, Budget, Used ซึ่งเปิดบริการ Service ไว้ 3 ตัวคือ
http://localhost/nusoap/WebServiceServer_Login.php?wsdl
(ใช้ตรวจสอบการ Login ของ Client)
http://localhost/nusoap/WebServiceServer_Show.php?wsdl
(ใช้สำหรับส่งข้อมูลรายละเอียดของลูกค้าไปยัง Client)
http://localhost/nusoap/WebServiceServer_Save.php?wsdl
(ใช้สำหรับ Update ข้อมูลจาก Client เมื่อมีการแก้ไขและส่งข้อมูลใหม่มายัง Web Service ฝั่ง Server)
โดย User ในฝั่ง Client สามารถเขียน Web Service เพื่อตรวจสอบข้อมูล Username และ Password ผ่าน Form และเมื่อ Login ผ่าน ฝั่ง Client สามารถทำการเรียกข้อมูลรายละเอียดต่าง ๆ ของลูกค้า รวมทั้ง สามารถทำการแก้ไขข้อมูลใหม่ และส่งข้อมูลใหม่มายัง Web Service ฝั่ง Server ได้ (ดูภาพประกอบเพื่อความเข้าใจ)
ก่อนอ่านบทความนี้ควรอ่าน 3 บทความนี้ก่อน
ฐานข้อมูลฝั่ง Server
CREATE TABLE `customer` (
`CustomerID` varchar(4) NOT NULL,
`Username` varchar(30) NOT NULL,
`Password` varchar(30) NOT NULL,
`Name` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`CountryCode` varchar(2) NOT NULL,
`Budget` double NOT NULL,
`Used` double NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `customer`
--
INSERT INTO `customer` VALUES ('C001', 'win', 'win001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'john', 'john002', 'John Smith', '[email protected]', 'EN', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'jame', 'jame003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'chalee', 'chalee004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);
นำคำสั่ง SQL นี้ไปสร้าง Database ในฝั่งของ Web Service Server

เมื่อสร้างเสร็จจะได้โครงสร้างและข้อมูลดังรูป
สำหรับบทความนี้ใช้ Library ของ NuSoap สามารถดาวน์โหลดได้ที่
หรือจะดาวน์โหลดได้จากในส่วนท้ายของบทความ
Code เต็ม ๆ
Web Service ฝั่ง Server ที่เป็น PHP
WebServiceServer_Login.php ใช้ตรวจสอบการ Login ของ Client
<?php
require_once("lib/nusoap.php");
//Create a new soap server
$server = new soap_server();
//Define our namespace
$namespace = "http://localhost/nusoap/WebServiceServer_Login.php";
$server->wsdl->schemaTargetNamespace = $namespace;
//Configure our WSDL
$server->configureWSDL("CustomerLogin");
//Register our method and argument parameters
$varname = array(
'strUsername' => "xsd:string",
'strPassword' => "xsd:string"
);
// Register service and method
$server->register('chkCustomerLogin',$varname, array('return' => 'tns:ArrayOfString'));
//Add ComplexType with Array
$server->wsdl->addComplexType("ArrayOfString",
"complexType",
"array",
"",
"SOAP-ENC:Array",
array(),
array(array("ref"=>"SOAP-ENC:arrayType","wsdl:arrayType"=>"xsd:string[]")),
"xsd:string");
function chkCustomerLogin($strUsername,$strPassword)
{
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("mydatabase");
$strSQL = "
SELECT * FROM customer WHERE 1
AND Username = '".$strUsername."'
AND Password = '".$strPassword."'
";
$objQuery = mysql_query($strSQL) or die (mysql_error());
$objResult = mysql_fetch_array($objQuery);
if($objResult)
{
$arr[0] = true;
$arr[1] = $objResult["CustomerID"];
$arr[2] = null;
}
else
{
$arr[0] = false;
$arr[1] = null;
$arr[2] = "Invalid username or password";
}
/***
$arr[0] // Return Status Login false or true
$arr[1] // Return CustomerID
$arr[2] // Return Error Message
*/
mysql_close();
return $arr;
}
// Get our posted data if the service is being consumed
// otherwise leave this data blank.
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
// pass our posted data (or nothing) to the soap service
$server->service($POST_DATA);
exit();
?>
WebServiceServer_Show.php ใช้สำหรับส่งข้อมูลรายละเอียดของลูกค้าไปยัง Client
<?php
require_once("lib/nusoap.php");
//Create a new soap server
$server = new soap_server();
//Define our namespace
$namespace = "http://localhost/nusoap/WebServiceServer_Show.php";
$server->wsdl->schemaTargetNamespace = $namespace;
//Configure our WSDL
$server->configureWSDL("getCustomer");
//Add ComplexType
$server->wsdl->addComplexType(
'DataList',
'complexType',
'struct',
'all',
'',
array(
'CustomerID' => array('name' => 'CustomerID', 'type' => 'xsd:string'),
'Username' => array('name' => 'Username', 'type' => 'xsd:string'),
'Password' => array('name' => 'Password', 'type' => 'xsd:string'),
'Name' => array('name' => 'Name', 'type' => 'xsd:string'),
'Email' => array('name' => 'Email', 'type' => 'xsd:string'),
'CountryCode' => array('name' => 'CountryCode', 'type' => 'xsd:string'),
'Budget' => array('name' => 'Budget', 'type' => 'xsd:float'),
'Used' => array('name' => 'Used', 'type' => 'xsd:float')
)
);
//Add ComplexType
$server->wsdl->addComplexType(
'DataListResult',
'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(
array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:DataList[]')
),
'tns:DataList'
);
//Register our method and argument parameters
$varname = array(
'strCustomerID' => "xsd:string"
);
// Register service and method
$server->register('resultCustomer', // method name
$varname, // input parameters
array('return' => 'tns:DataListResult'));
function resultCustomer($strCustomerID)
{
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM customer WHERE 1 AND CustomerID = '".$strCustomerID."' ";
$objQuery = mysql_query($strSQL) or die (mysql_error());
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($objConnect);
return $resultArray;
}
// Get our posted data if the service is being consumed
// otherwise leave this data blank.
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
// pass our posted data (or nothing) to the soap service
$server->service($POST_DATA);
exit();
?>
WebServiceServer_Save.php ใช้สำหรับ Update ข้อมูลจาก Client เมื่อมีการแก้ไขและส่งข้อมูลใหม่มายัง Web Service ฝั่ง Server
<?php
require_once("lib/nusoap.php");
//Create a new soap server
$server = new soap_server();
//Define our namespace
$namespace = "http://localhost/nusoap/WebServiceServer_Save.php";
$server->wsdl->schemaTargetNamespace = $namespace;
//Configure our WSDL
$server->configureWSDL("UpdateCustomer");
//Register our method and argument parameters
$varname = array(
'strCustomerID' => "xsd:string",
'strPassword' => "xsd:string",
'strName' => "xsd:string",
'strEmail' => "xsd:string",
'strCountryCode' => "xsd:string",
'strBudget' => "xsd:float",
'strUsed' => "xsd:float"
);
// Register service and method
$server->register('saveUpdateCustomer',$varname, array('return' => 'tns:ArrayOfString'));
//Add ComplexType with Array
$server->wsdl->addComplexType("ArrayOfString",
"complexType",
"array",
"",
"SOAP-ENC:Array",
array(),
array(array("ref"=>"SOAP-ENC:arrayType","wsdl:arrayType"=>"xsd:string[]")),
"xsd:string");
//Method update
function saveUpdateCustomer($strCustomerID,
$strPassword,
$strName,
$strEmail,
$strCountryCode,
$strBudget,
$strUsed)
{
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("mydatabase");
$strSQL = "
UPDATE customer SET
Password = '".$strPassword."',
Name = '".$strName."',
Email = '".$strEmail."',
CountryCode = '".$strCountryCode."',
Budget = '".$strBudget."',
Used = '".$strUsed."'
WHERE CustomerID = '".$strCustomerID."'
";
$objQuery = mysql_query($strSQL);
if($objQuery)
{
$arr[0] = true;
$arr[1] = null;
}
else
{
$arr[0] = false;
$arr[1] = mysql_error();
}
/***
$arr[0] // Return Status Update
$arr[1] // Return Error Message
*/
mysql_close();
return $arr;
}
// Get our posted data if the service is being consumed
// otherwise leave this data blank.
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
// pass our posted data (or nothing) to the soap service
$server->service($POST_DATA);
exit();
?>
Web Service ฝั่ง Client ด้วย ASP.NET
สร้างไฟล์สำหรับ Client เพื่อทดสอบเรียก Web Sevice ด้วย ASP.NET

ให้สร้าง Project ที่เป็น ASP.NET Web Application หรือ ASP.NET WebSite สำหรับภาษาจะเลือก VB.NET หรือ C# ก็แล้วแต่ถนัดครับ เพราะในบทความนี้มีทั้ง VB.NET และ C#

เพิ่มไฟล์ Webpage (.aspx) ประกอบด้วย 3 ไฟล์คือ frmLogin.aspx , frmShow.aspx , frmProfile.aspx
- frmLogin.aspx ไฟล์สำหรับ Web Service เพื่อเรียกสถานะการ Login โดยออกแบบ Screen ดังรูป

- frmShow.aspx ไฟล์สำหรับ Web Service เมื่อหลัง Login ผ่านจะดึงข้อมูลลูกค้ามาแสดง

- frmProfile.aspx ไฟล์สำหรับ Web Service ที่จะทำการแก้ไขข้อมูลและส่งไป Update ยัง Web Service ฝั่ง Server ของ PHP

Add Web Reference ของ Web Service ทั้ง 3 ตัว

http://localhost/nusoap/WebServiceServer_Login.php?wsdl
ตั้งชื่อ Web reference name เป็น clsCustomerLogin

http://localhost/nusoap/WebServiceServer_Show.php?wsdl
ตั้งชื่อ Web reference name เป็น clsGetCustomer

http://localhost/nusoap/WebServiceServer_Save.php?wsdl
ตั้งชื่อ Web reference name เป็น clsUpdateCustomer
หลังจากทำตามขั้นตอนทั้งหมดเรียบร้อยแล้ว ให้สร้าง Event ในแต่ล่ะ Form ดังนี้ (หรือจะดาวน์โหลด Code ทั้งหมดได้จากส่วนล่างของบทความ)
Screen frmLogin.aspx
- สำหรับ VB.NET
frmLogin.aspx.vb
Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLogin.Click
Dim clsLogin As New clsCustomerLogin.CustomerLogin
Dim myArr As Array = clsLogin.chkCustomerLogin(Me.txtUsername.Text, Me.txtPassword.Text)
If CStr(myArr(0)) = "1" Then
Session("strCustomerID") = myArr(1).ToString()
Response.Redirect("frmShow.aspx")
Else
Me.ClientScript.RegisterStartupScript(Me.GetType(), "myalert", "alert('" & myArr(2) & "');", True)
End If
End Sub
- สำหรับ C#
frmLogin.aspx.cs
protected void btnLogin_Click(object sender, EventArgs e)
{
clsCustomerLogin.CustomerLogin clsLogin = new clsCustomerLogin.CustomerLogin();
Array myArr = (Array)clsLogin.chkCustomerLogin(this.txtUsername.Text, this.txtPassword.Text);
if (Convert.ToString(myArr.GetValue(0)) == "1")
{
Session["strCustomerID"] = myArr.GetValue(1).ToString();
Response.Redirect("frmShow.aspx");
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myArr.GetValue(2).ToString() + "');", true);
}
}
Screenshot

หน้าจอตรวจสอบ Username และ Password โดยจะส่งข้อมูลไปตรวจสอบยัง Web Service ฝั่ง Server

กรณีที่ Login ไม่ถูกต้อง จะมีการแสดง Error message ที่ถูกส่งมายัง Web Service ฝั่ง Server
Screen frmShow.aspx
- สำหรับ VB.NET
frmShow.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsNothing(Session("strCustomerID")) Then
Response.Redirect("frmLogin.aspx")
Response.End()
End If
Dim cls As New clsGetCustomer.getCustomer
Dim myArr As Array = cls.resultCustomer(Session("strCustomerID"))
If myArr.Length > 0 Then
Me.lblCustomerID.Text = DataBinder.Eval(myArr(0), "CustomerID").ToString()
Me.lblUsername.Text = DataBinder.Eval(myArr(0), "Username").ToString()
Me.lblPassword.Text = DataBinder.Eval(myArr(0), "Password").ToString()
Me.lblName.Text = DataBinder.Eval(myArr(0), "Name").ToString()
Me.lblEmail.Text = DataBinder.Eval(myArr(0), "Email").ToString()
Me.lblCountryCode.Text = DataBinder.Eval(myArr(0), "CountryCode").ToString()
Me.lblBudget.Text = DataBinder.Eval(myArr(0), "Budget").ToString()
Me.lblUsed.Text = DataBinder.Eval(myArr(0), "Used").ToString()
End If
End Sub
- สำหรับ C#
frmShow.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if ((Session["strCustomerID"] == null))
{
Response.Redirect("frmLogin.aspx");
Response.End();
}
clsGetCustomer.getCustomer cls = new clsGetCustomer.getCustomer();
Array myArr = cls.resultCustomer(Session["strCustomerID"].ToString());
if (myArr.Length > 0)
{
this.lblCustomerID.Text = DataBinder.Eval(myArr.GetValue(0), "CustomerID").ToString();
this.lblUsername.Text = DataBinder.Eval(myArr.GetValue(0), "Username").ToString();
this.lblPassword.Text = DataBinder.Eval(myArr.GetValue(0), "Password").ToString();
this.lblName.Text = DataBinder.Eval(myArr.GetValue(0), "Name").ToString();
this.lblEmail.Text = DataBinder.Eval(myArr.GetValue(0), "Email").ToString();
this.lblCountryCode.Text = DataBinder.Eval(myArr.GetValue(0), "CountryCode").ToString();
this.lblBudget.Text = DataBinder.Eval(myArr.GetValue(0), "Budget").ToString();
this.lblUsed.Text = DataBinder.Eval(myArr.GetValue(0), "Used").ToString();
}
}
Screenshot

หลังจาก Login ผ่านจะมีการเก็บ CustomerID ลงในตัวแปร Session และหลังจากนั้นก็จะ redirect มายังหน้า frmShow.aspx โดยหน้านี้จะเรียก Web Service ของ Server เพื่อดึงรายละเอียดของลูกค้ามาแสดง (ตามตัวอย่าง) ลองคลิกที่ Edit Your Profile เพื่อแก้ไขข้อมูล
Screen frmProfile.aspx
- สำหรับ VB.NET
frmProfile.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsNothing(Session("strCustomerID")) Then
Response.Redirect("frmLogin.aspx")
Response.End()
End If
If Not Page.IsPostBack Then
BindData()
End If
End Sub
Protected Sub BindData()
Dim cls As New clsGetCustomer.getCustomer
Dim myArr As Array = cls.resultCustomer(Session("strCustomerID"))
If myArr.Length > 0 Then
Me.lblCustomerID.Text = DataBinder.Eval(myArr(0), "CustomerID").ToString()
Me.lblUsername.Text = DataBinder.Eval(myArr(0), "Username").ToString()
Me.txtPassword.Text = DataBinder.Eval(myArr(0), "Password").ToString()
Me.txtName.Text = DataBinder.Eval(myArr(0), "Name").ToString()
Me.txtEmail.Text = DataBinder.Eval(myArr(0), "Email").ToString()
Me.txtCountryCode.Text = DataBinder.Eval(myArr(0), "CountryCode").ToString()
Me.txtBudget.Text = DataBinder.Eval(myArr(0), "Budget").ToString()
Me.txtUsed.Text = DataBinder.Eval(myArr(0), "Used").ToString()
End If
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Dim cls As New clsUpdateCustomer.UpdateCustomer
Dim myArr As Array = cls.saveUpdateCustomer(Session("strCustomerID"), _
Me.txtPassword.Text, _
Me.txtName.Text, _
Me.txtEmail.Text, _
Me.txtCountryCode.Text, _
Me.txtBudget.Text, _
Me.txtUsed.Text)
If CStr(myArr(0)) = "1" Then
Me.ClientScript.RegisterStartupScript(Me.GetType(), "myalert", "alert('Update Successfully ');window.location='frmShow.aspx';", True)
Else
Me.ClientScript.RegisterStartupScript(Me.GetType(), "myalert", "alert('Update Failed error..." & Replace(myArr(1), "'", "\'") & "');", True)
End If
End Sub
- สำหรับ C#
frmProfile.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if ((Session["strCustomerID"] == null))
{
Response.Redirect("frmLogin.aspx");
Response.End();
}
if (!Page.IsPostBack)
{
BindData();
}
}
protected void BindData()
{
clsGetCustomer.getCustomer cls = new clsGetCustomer.getCustomer();
Array myArr = cls.resultCustomer(Session["strCustomerID"].ToString());
if (myArr.Length > 0)
{
this.lblCustomerID.Text = DataBinder.Eval(myArr.GetValue(0), "CustomerID").ToString();
this.lblUsername.Text = DataBinder.Eval(myArr.GetValue(0), "Username").ToString();
this.txtPassword.Text = DataBinder.Eval(myArr.GetValue(0), "Password").ToString();
this.txtName.Text = DataBinder.Eval(myArr.GetValue(0), "Name").ToString();
this.txtEmail.Text = DataBinder.Eval(myArr.GetValue(0), "Email").ToString();
this.txtCountryCode.Text = DataBinder.Eval(myArr.GetValue(0), "CountryCode").ToString();
this.txtBudget.Text = DataBinder.Eval(myArr.GetValue(0), "Budget").ToString();
this.txtUsed.Text = DataBinder.Eval(myArr.GetValue(0), "Used").ToString();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
clsUpdateCustomer.UpdateCustomer cls = new clsUpdateCustomer.UpdateCustomer();
Array myArr = cls.saveUpdateCustomer(Session["strCustomerID"].ToString(), this.txtPassword.Text, this.txtName.Text, this.txtEmail.Text, this.txtCountryCode.Text, Convert.ToInt32(this.txtBudget.Text), Convert.ToInt32(this.txtUsed.Text));
if (Convert.ToString(myArr.GetValue(0)) == "1")
{
this.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Update Successfully ');window.location='frmShow.aspx';", true);
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Update Failed error..." + myArr.GetValue(1).ToString().Replace("'","\\'") + "');", true);
}
}
Screenshot

หน้าจอนี้สำหรับดึงข้อมูลผ่าน Web Service ที่อยู่ในฝั่ง Server มาใส่ใน Form เพื่อรอการแก้ไข ในตัวอย่างจะลองแก้ไขข้อมูล Name ของลูกค้า

กรณีที่ Update ผ่านโปรแกรมจะส่งค่ามาเป็น true จากใน code เขียนเงื่อนไขให้แสดงดังภาพ

กรณีที่ Error ทางฝั่ง Web Service Server ก็มีการ return ค่า error message แล้วแต่ว่าจะ error อะไร สามารถเขียนเงื่อนไขเพิ่มได้ที่ไฟล์ (WebServiceServer_Save.php)

หลังจากที่ Update เสร็จ ก็จะเห็นข้อมูลเปลี่ยนแลงดังรูป

เมื่อกลับไปดู Database ผ่าน phpMyAdmin ของ Web Service ฝั่ง Server ที่เป็น PHP ก็จะเห็นว่าข้อมูลที่แก้ไขได้ถูกเปลี่ยนแปลงไป
ดาวน์โหลด Code ทั้งหมด ทั้งที่เป็น PHP Web Service และ ASP.NET by VB.NET or C#
Download Code !!
บทความอื่น ๆ ที่เกี่ยวข้อง
Go to : การทำ Login Form และ Update MySQL Data ผ่าน Web Service ด้วย PHP (NuSoap)
Go to : วิธีการสร้าง PHP กับ Web Service และ Return Array ไปยัง Client ด้วย NuSoap
Go to : PHP - Web Service กับ MySQL รับส่งค่าผ่าน Web Service กับ MySQL (NuSoap)
Go to : PHP Create - Call Web Service สร้างและเรียกเว็บเซอร์วิส ด้วย PHP (NuSoap and Soap)
Go to : PHP สร้าง Web Service และใช้ .NET เรียก Web Service ของ PHP (ASP.NET and Windows Form)
Go to : php กับ web service ขอคำปรึกษาเรื่องการ return array ใน webservice ครับ
|
|
|
|
 |
|
|
|
|
|
|
|
|
|
|
|
By : |
TC Admin
|
|
Score Rating : |
- |
|
Create Date : |
2012-05-21 21:01:28 |
|
Download : |
No files |
|
|
|
|
|