Windows Phone Delete data in Web Server |
Windows Phone Delete data in Web Server บทความและตัวอย่าง App การใช้ Windows Phone ทำการลบ Delete ข้อมูลที่อยู่บน Web Server ที่ทำงานด้วย php กับ MySQL วิธ๊นี้เราจะใช้การ Request แบบ REST คือจะส่งค่า POST ไปยัง URL ปลายทาง พร้อมกับ Parameters ค่าที่ต้องการลบ และ URL ปลายทางจะต้องออกแบบโปรแกรมที่จะทำหน้าที่รับค่าจาก Windows Phone และอ่าน Parameters พร้อมกับนำค่าที่ได้ไปลบข้อมูลใน Database และทำการส่งค่ากลับมาให้กับ Windows Phone ได้ทราบ
Windows Phone Delete data in Web Server
Web Server ออกแบบโปรแกรมสำหรับการลบข้อมูล
member
CREATE TABLE `member` (
`MemberID` int(2) NOT NULL auto_increment,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Name` varchar(50) NOT NULL,
`Tel` varchar(50) NOT NULL,
`Email` varchar(150) NOT NULL,
PRIMARY KEY (`MemberID`),
UNIQUE KEY `Username` (`Username`),
UNIQUE KEY `Email` (`Email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `member`
--
INSERT INTO `member` VALUES (1, 'weerachai', 'weerachai@1', 'Weerachai Nukitram', '0819876107', '[email protected]');
INSERT INTO `member` VALUES (2, 'adisorn', 'adisorn@2', 'Adisorn Bunsong', '021978032', '[email protected]');
INSERT INTO `member` VALUES (3, 'surachai', 'surachai@3', 'Surachai Sirisart', '0876543210', '[email protected]');
INSERT INTO `member` VALUES (4, 'surapong', 'surapong@4', 'Surapong Siriphun', '0812345678', '[email protected]');
โครงสร้างตาราง MySQL บน Web Server
showAllData.php ไฟล์ php ที่ทำหน้าที่แสดงข้อมูลทั้งหมดจาก MySQL Database
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM member WHERE 1 ORDER BY MemberID ASC ";
$objQuery = mysql_query($strSQL);
$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);
echo json_encode($resultArray);
?>
deleteData.php ไฟล์ที่ทำหน้าที่ Delete ลบข้อมูล
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
// $_POST["sMemberID"] = "1"; // for Sample
$strMemberID = $_POST["sMemberID"];
$strSQL = "DELETE FROM member WHERE 1 AND MemberID = '".$strMemberID."' ";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "0|Cannot delete data!";
exit();
}
else
{
echo "1|";
exit();
}
/**
return
x|y
x // (0=Failed , 1=Complete)
y // Error Message
*/
mysql_close($objConnect);
?>
ไฟล์ php ที่ทำหน้าที่ Delete ลบข้อมูลบน MySQL ที่ถุกส่ง Request มาจาก Windows Phone Client
Windows Phone Project
MainPage.xaml
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Margin="0,0,-12,0" x:Name="MemberList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Button Content="Del" Height="72" Tag="{Binding MemberID}" HorizontalAlignment="Left" Name="btnDel" Click="ClickDelete" VerticalAlignment="Top" Width="108" />
<TextBlock Text="{Binding Username}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Tel}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Email}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
MainPage.xaml.vb (VB.NET)
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Json
Imports System.Collections.ObjectModel
Imports System.IO
Imports System.Text
Partial Public Class MainPage
Inherits PhoneApplicationPage
' Constructor
Public Sub New()
InitializeComponent()
AddHandler Loaded, AddressOf MainPage_Loaded
End Sub
Dim prog As ProgressIndicator
Private Sub MainPage_Loaded(sender As Object, e As System.Windows.RoutedEventArgs)
LoadData()
End Sub
Private Sub LoadData()
Dim url As String = "http://localhost/myphp/showAllData.php"
Dim uri As Uri = New Uri(url, UriKind.Absolute)
Dim postData As StringBuilder = New StringBuilder()
postData.AppendFormat("{0}={1}", "NULL", HttpUtility.UrlEncode(""))
Dim client As WebClient
client = New WebClient()
client.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
client.Headers(HttpRequestHeader.ContentLength) = postData.Length.ToString()
AddHandler client.UploadStringCompleted, AddressOf client_UploadStringCompleted
AddHandler client.UploadProgressChanged, AddressOf client_UploadProgressChanged
client.UploadStringAsync(uri, "POST", postData.ToString())
prog = New ProgressIndicator()
prog.IsVisible = True
prog.IsIndeterminate = True
prog.Text = "Downloading...."
SystemTray.SetProgressIndicator(Me, prog)
End Sub
Private Sub client_UploadProgressChanged(sender As Object, e As UploadProgressChangedEventArgs)
'Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%"
End Sub
Private Sub client_UploadStringCompleted(sender As Object, e As UploadStringCompletedEventArgs)
If e.Cancelled = False And e.Error Is Nothing Then
Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(e.Result))
Dim list As New ObservableCollection(Of Member)()
Dim serializer As New DataContractJsonSerializer(GetType(ObservableCollection(Of Member)))
list = DirectCast(serializer.ReadObject(ms), ObservableCollection(Of Member))
Dim myMember As New List(Of Member)
For Each cm As Member In list
Dim sMemberID As String = cm.MemberID.ToString()
Dim sUsername As String = cm.Username.ToString()
Dim sPassword As String = cm.Password.ToString()
Dim sName As String = cm.Name.ToString()
Dim sTel As String = cm.Tel.ToString()
Dim sEmail As String = cm.Email.ToString()
myMember.Add(New Member(sMemberID, sUsername, sPassword, sName, sTel, sEmail))
Next
Me.MemberList.ItemsSource = myMember
prog.IsVisible = False
End If
End Sub
Private Sub ClickDelete(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim btnDel As Button = DirectCast(e.OriginalSource, Button)
If MessageBox.Show("Are you sure?", "Delete ", MessageBoxButton.OKCancel) = MessageBoxResult.OK Then
'*** Delete Data ***'
Dim url As String = "http://localhost/myphp/deleteData.php"
Dim uri As Uri = New Uri(url, UriKind.Absolute)
Dim postData As StringBuilder = New StringBuilder()
postData.AppendFormat("{0}={1}", "sMemberID", HttpUtility.UrlEncode(btnDel.Tag.ToString()))
Dim client As WebClient
client = New WebClient()
client.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
client.Headers(HttpRequestHeader.ContentLength) = postData.Length.ToString()
AddHandler client.UploadStringCompleted, AddressOf client_DeleteUploadStringCompleted
client.UploadStringAsync(uri, "POST", postData.ToString())
prog = New ProgressIndicator()
prog.IsVisible = True
prog.IsIndeterminate = True
prog.Text = "Deleting...."
SystemTray.SetProgressIndicator(Me, prog)
End If
End Sub
Private Sub client_DeleteUploadStringCompleted(sender As Object, e As UploadStringCompletedEventArgs)
If e.Cancelled = False And e.Error Is Nothing Then
prog.IsVisible = False
MessageBox.Show("Delete Completed.", "Result", MessageBoxButton.OK)
LoadData()
End If
End Sub
<DataContract()> _
Public Class Member
<DataMember()> _
Public Property MemberID() As String
Get
Return m_MemberID
End Get
Set(value As String)
m_MemberID = value
End Set
End Property
<DataMember()> _
Public Property Username() As String
Get
Return m_Username
End Get
Set(value As String)
m_Username = value
End Set
End Property
<DataMember()> _
Public Property Password() As String
Get
Return m_Password
End Get
Set(value As String)
m_Password = value
End Set
End Property
<DataMember()> _
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
<DataMember()> _
Public Property Tel() As String
Get
Return m_Tel
End Get
Set(value As String)
m_Tel = value
End Set
End Property
<DataMember()> _
Public Property Email() As String
Get
Return m_Email
End Get
Set(value As String)
m_Email = value
End Set
End Property
Private m_MemberID As String
Private m_Username As String
Private m_Password As String
Private m_Name As String
Private m_tel As String
Private m_Email As String
Public Sub New(ByVal strMemberID As String,
ByVal strUsername As String,
ByVal strPassword As String,
ByVal strName As String,
ByVal strTel As String,
ByVal strEmail As String)
Me.MemberID = strMemberID
Me.Username = strUsername
Me.Password = strPassword
Me.Name = strName
Me.Tel = strTel
Me.Email = strEmail
End Sub
End Class
End Class
MainPage.xaml.cs (C#)
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using Microsoft.Phone.Shell;
using System.Windows.Controls;
using System.Net;
namespace PhoneApp
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
ProgressIndicator prog;
private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
string url = "http://localhost/myphp/showAllData.php";
Uri uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "NULL", HttpUtility.UrlEncode(""));
WebClient client = default(WebClient);
client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
client.UploadStringCompleted += client_UploadStringCompleted;
client.UploadProgressChanged += client_UploadProgressChanged;
client.UploadStringAsync(uri, "POST", postData.ToString());
prog = new ProgressIndicator();
prog.IsVisible = true;
prog.IsIndeterminate = true;
prog.Text = "Downloading....";
SystemTray.SetProgressIndicator(this, prog);
}
private void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
//Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%"
}
private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Cancelled == false & e.Error == null)
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
ObservableCollection<Member> list = new ObservableCollection<Member>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Member>));
list = (ObservableCollection<Member>)serializer.ReadObject(ms);
List<Member> myMember = new List<Member>();
foreach (Member cm in list)
{
string sMemberID = cm.MemberID.ToString();
string sUsername = cm.Username.ToString();
string sPassword = cm.Password.ToString();
string sName = cm.Name.ToString();
string sTel = cm.Tel.ToString();
string sEmail = cm.Email.ToString();
myMember.Add(new Member(sMemberID, sUsername, sPassword, sName, sTel, sEmail));
}
this.MemberList.ItemsSource = myMember;
prog.IsVisible = false;
}
}
private void ClickDelete(object sender, RoutedEventArgs e)
{
Button btnDel = (Button)e.OriginalSource;
if (MessageBox.Show("Are you sure?", "Delete ", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
//*** Delete Data ***'
string url = "http://localhost/myphp/deleteData.php";
Uri uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "sMemberID", HttpUtility.UrlEncode(btnDel.Tag.ToString()));
WebClient client = default(WebClient);
client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
client.UploadStringCompleted += client_DeleteUploadStringCompleted;
client.UploadStringAsync(uri, "POST", postData.ToString());
prog = new ProgressIndicator();
prog.IsVisible = true;
prog.IsIndeterminate = true;
prog.Text = "Deleting....";
SystemTray.SetProgressIndicator(this, prog);
}
}
private void client_DeleteUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Cancelled == false & e.Error == null)
{
prog.IsVisible = false;
MessageBox.Show("Delete Completed.", "Result", MessageBoxButton.OK);
LoadData();
}
}
[DataContract]
public class Member
{
[DataMember]
public string MemberID { get; set; }
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Tel { get; set; }
[DataMember]
public string Email { get; set; }
public Member(string strMemberID, string strUsername, string strPassword
, string strName
, string strTel
, string strEmail)
{
this.MemberID = strMemberID;
this.Username = strUsername;
this.Password = strPassword;
this.Name = strName;
this.Tel = strTel;
this.Email = strEmail;
}
}
}
}
ในตัวอย่างนี้มี Code ทั้งที่เป็น VB.NET และ C# และสามารถดาวน์โหลด All Code ทั้งหมดได้จากส่วนท้ายของบทความ (Login สมาชิกก่อน)
Screenshot
แสดงรายการข้อมูลจาก Web Server ให้คลิกที่ Del เพื่อลบข้อมูล
จะมีการถาม Confirm การลบข้อมูล
แสดงการลบข้อมูลเรียบร้อย
ข้อมูลใน ListBox จะหายไปหลังจากการลบ
ข้อมูลใน Dataase ของ Web Server ก็จะหายไปเช่นเดียวกัน
.
|