Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone



Clound SSD Virtual Server

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

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

Windows Phone Delete data in 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

Windows Phone Delete data in Web Server

    <!--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

Windows Phone Delete data in Web Server

แสดงรายการข้อมูลจาก Web Server ให้คลิกที่ Del เพื่อลบข้อมูล

Windows Phone Delete data in Web Server

จะมีการถาม Confirm การลบข้อมูล

Windows Phone Delete data in Web Server

แสดงการลบข้อมูลเรียบร้อย

Windows Phone Delete data in Web Server

ข้อมูลใน ListBox จะหายไปหลังจากการลบ

Windows Phone Delete data in Web Server

ข้อมูลใน Dataase ของ Web Server ก็จะหายไปเช่นเดียวกัน


.

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-09-15 13:49:44 / 2017-03-25 21:52:20
  Download : Download  Windows Phone Delete data in Web Server
 Sponsored Links / Related

 
การสร้าง ApplicationBar (MenuItem) บน Windows Phone
Rating :

 
Dynamically Create Controls AddHandler (Event Handler) บน Windows Phone
Rating :

 
ตัวอย่างโปรแกรม Code Samples สำหรับ Windows Phone
Rating :

 
Windows Phone Posting Data to Web Server URL (Website)
Rating :

 
Windows Phone Show List Data from Web Server (Website)
Rating :

 
Windows Phone Search Data from Web Server
Rating :

 
Windows Phone Edit Update data to Web Server
Rating :

 
Windows Phone and BackgroundWorker
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 03
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่