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

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

iOS/iPhone Delete Remove Data on Web Server (URL,Website) บทความการเขียน iOS ทำงานในรูปแบบของ Client และ Server ใการที่จะลบ Delete ข้อมูลที่อยู่บน Web Server โดยใช้ iOS ทำหน้าที่เป็น Client ทำการ Request รายการข้อมูลทั้งหมดมาแสดงบน Table View และทำการส่งรายการที่จะลบไปยัง Web Server อีกครั้ง โดยฝั่ง Web Server ใช้ PHP กับ MySQL ทำการจัดเก็บและลบข้อมูลต่าง ๆ ที่ถูก Request มาจาก iOS

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

iOS/iPhone Delete Remove Data on Web Server (URL,Website)


หลักการนั้นฝั่ง Web Server ที่เป็น PHP กับ MySQL จะออกแบบไฟล์ php ขึ้นมา 2 ไฟล์คือ (1) ไฟล์สำหรับแสดงรายการข้อมูลทั้งหมด และ (2) ไฟล์สำหรับรับ Request เพื่อลบข้อมูลใน Cell นั้น ๆ ที่ได้ส่งมาจาก iOS Client โดยทั้งหมดนี้ใช้ JSON ในการที่จะรับส่งข้อมูลต่าง ๆ เช่นเดิม

และที่ขาดไม่ได้คือ Interface ของ Table View ที่จะใช้จัดการกับ Mode ต่าง ๆ ของ Table View เช่น แสดง Icons สำหรับ Delete ถือว่า Table View นั้นสะดวกมาก ๆ โดยสามารถอ่าน Basic Table View เกี่ยวกับ Mode การ Delete ได้ที่บทความนี้

iOS/iPhone Table View Show Enable Edit / Delete Cell (Swipe To Delete) (UITableView)


Example การเขียน iOS เพื่อลบ Delete ข้อมูลที่อยู่บน Web Server

MySQL Database
CREATE TABLE `member` (
  `MemberID` int(11) NOT NULL auto_increment,
  `Name` varchar(50) NOT NULL,
  `Tel` varchar(50) NOT NULL,
  PRIMARY KEY  (`MemberID`)
) ENGINE=MyISAM  AUTO_INCREMENT=4 ;

-- 
-- Dumping data for table `member`
-- 

INSERT INTO `member` VALUES (1, 'Weerachai', '0819876107');
INSERT INTO `member` VALUES (2, 'Win', '021978032');
INSERT INTO `member` VALUES (3, 'Eak', '0876543210');

โครงสร้างของ MySQL Database

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

getData.php ไฟล์ php สำหรับแสดงข้อมูลทั้งหมดใน Table View (TableView)
<?php
	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");
	$strSQL = "SELECT * FROM member WHERE 1  ";
	$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 ไฟล์ php สำหรับทำการรับค่า POST ที่ถูก Request เพื่อลบข้อมูล
<?php
	/*** for Sample 
		$_POST["sMemberID"] = "1";
	*/

	$strMemberID = $_POST["sMemberID"];

	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");

	/*** Insert ***/
	$strSQL = "DELETE member 
		WHERE MemberID = '".$strMemberID."' ";

	$objQuery = mysql_query($strSQL);

	$arr = null;
	if(!$objQuery)
	{
		$arr["Status"] = "0";
		$arr["Message"] = "Delete Data Failed";
	}
	else
	{
		$arr["Status"] = "1";
		$arr["Message"] = "Delete Data Successfully";
	}
	
	echo json_encode($arr);
?>









iOS/iPhone Delete Remove Data on Web Server (URL,Website)

เริ่มต้นด้วยการสร้าง Application บน Xcode แบบ Single View Application

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

เลือกและไม่เลือกรายการดังรูป

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

ตอนนี้หน้าจอ View จะยังว่าง ๆ

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

ลาก Navigation Bar มาวางไว้บนหน้าจอ View ทำการแก้ไข Title ให้เรียบร้อย

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

ตามด้วย Bar Button Item เลือกเป็นแบบ Edit

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

แล้วก็ Table View มาวางไว้บนหน้าจอ View

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

คลิกขวาที่ Table View แล้วทำการเชื่อม dataSource และ delegate กับ File's Owner

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

ใน Class ของ .h ให้ทำการเชื่อม IBOutlet และ IBAction ดังรูป จากนั้นเขียน Code ต่าง ๆ ดังนี้

ViewController.h
//
//  ViewController.h
//  deleteDataServer
//
//  Created by Weerachai on 12/10/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController  <UITableViewDataSource,UITableViewDelegate>
{
    
    IBOutlet UITableView *myTable;
    
    IBOutlet UIBarButtonItem *itemEdit;
    
}

@property(nonatomic,assign) NSMutableData *receivedData;

- (IBAction)btnEdit:(id)sender;

@end









ViewController.m
//
//  ViewController.m
//  deleteDataServer
//
//  Created by Weerachai on 12/10/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    BOOL boolDelete;
    
    NSMutableArray *myObject;
    
    // A dictionary object
    NSDictionary *dict;
    
    // Define keys
    NSString *memberid;
    NSString *name;
    NSString *tel;
    
    
    UIAlertView *loading;
    
    NSString *modeAction;
}

@end

@implementation ViewController

@synthesize receivedData;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    boolDelete = FALSE;
    
    
    // Define keys
    memberid = @"MemberID";
    name = @"Name";
    tel = @"Tel";
    
    // Create array to hold dictionaries
    myObject = [[NSMutableArray alloc] init];
    
    modeAction = @"LOAD";
    
    // for Load Data to List View
    if([modeAction isEqualToString:@"LOAD"] ){
        
        NSURLRequest *theRequest =
        [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.thaicreate.com/url/getData.php"]
                 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                 timeoutInterval:10.0];
        
        NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        
        // Loading...
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        loading = [[UIAlertView alloc] initWithTitle:@"" message:@"Please Wait..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
        UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
        progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        [loading addSubview:progress];
        [progress startAnimating];
        [progress release];
        [loading show];
        
        if (theConnection) {
            self.receivedData = nil;
        } else {
            UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"NSURLConnection " message:@"Failed in viewDidLoad"  delegate: self   cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [connectFailMessage show];
            [connectFailMessage release];
        }
        
    }
    
}

- (IBAction)btnEdit:(id)sender {

    if(!boolDelete)
    {
        boolDelete = TRUE;
        [myTable setEditing:YES animated:YES];
        [itemEdit setTitle:@"Cancel"];
    }
    else
    {
        boolDelete = FALSE;
        [myTable setEditing:NO animated:YES];
        [itemEdit setTitle:@"Edit"];
    }
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    receivedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    sleep(2);
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
    [connection release];
    [receivedData release];
    
    // inform the user
    UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: @"NSURLConnection " message: @"didFailWithError"  delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
    [didFailWithErrorMessage show];
    [didFailWithErrorMessage release];
	
    //inform the user
    NSLog(@"Connection failed! Error - %@", [error localizedDescription]);
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [loading dismissWithClickedButtonIndex:0 animated:YES];
    
    
    if(receivedData)
    {
        //NSLog(@"%@",receivedData);
        NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
        NSLog(@" abc = %@",dataString);
        
        // for Load Data
        if([modeAction isEqualToString:@"LOAD"] ){
            
            id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
            
            // values in foreach loop
            for (NSDictionary *dataDict in jsonObjects) {
                NSString *strMemberID = [dataDict objectForKey:@"MemberID"];
                NSString *strName = [dataDict objectForKey:@"Name"];
                NSString *strTel = [dataDict objectForKey:@"Tel"];
                
                dict = [NSDictionary dictionaryWithObjectsAndKeys:
                        strMemberID, memberid,
                        strName, name,
                        strTel, tel,
                        nil];
                [myObject addObject:dict];
            }
            
            // Reload Data
            [myTable reloadData];
        }
        
        // for Delete
        if([modeAction isEqualToString:@"DELETE"] ){
            
            // Return Status E.g : { "Status":"1", "Message":"Delete Data Successfully" }
            // 0 = Error
            // 1 = Completed
            
            id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
            
            // value in key name
            NSString *strStatus = [jsonObjects objectForKey:@"Status"];
            NSString *strMessage = [jsonObjects objectForKey:@"Message"];
            NSLog(@"Status = %@",strStatus);
            NSLog(@"Message = %@",strMessage);
            
            // Completed
            if( [strStatus isEqualToString:@"1"] ){
                UIAlertView *completed =[[UIAlertView alloc]
                                         initWithTitle:@": -) Completed!"
                                         message:strMessage delegate:self
                                         cancelButtonTitle:@"OK" otherButtonTitles: nil];
                [completed show];
            }
            else // Error
            {
                UIAlertView *error =[[UIAlertView alloc]
                                     initWithTitle:@": ( Error!"
                                     message:strMessage delegate:self
                                     cancelButtonTitle:@"OK" otherButtonTitles: nil];
                [error show];
            }
            
            // Reload Data After Delete
            [myTable reloadData];
            
            // Hide Delete
            [myTable setEditing:NO animated:YES];
            
        }
        
    }
    
    // release the connection, and the data object
    [connection release];
    [receivedData release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    int nbCount = [myObject count];
    if (nbCount == 0)
    {
        return 1;
    }
    else
    {
        return [myObject count];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // Use the default cell style.
        cell = [[[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                       reuseIdentifier : CellIdentifier] autorelease];
    }
    
    int nbCount = [myObject count];
    if (nbCount ==0)
    {
        cell.textLabel.text = @"";
        cell.detailTextLabel.text = @"";
    }
    else
    {
        NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
        
        // MemberID
        NSMutableString *text;
        text = [NSString stringWithFormat:@"MemberID : %@",[tmpDict objectForKey:memberid]];
        
        // Name & Tel
        NSMutableString *detail;
        detail = [NSString stringWithFormat:@"Name : %@ , Tel : %@"
                  ,[tmpDict objectForKey:name]
                  ,[tmpDict objectForKey:tel]];
        
        cell.textLabel.text = text;
        cell.detailTextLabel.text= detail;
        
        //[tmpDict objectForKey:memberid]
        //[tmpDict objectForKey:name]
        //[tmpDict objectForKey:tel]
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // to Delete
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //[myObject removeObjectAtIndex:indexPath.row];
        //[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        modeAction = @"DELETE";
        
        if([modeAction isEqualToString:@"DELETE"] ){
            
            // Get Index Delete
            NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
            
            //sMemberID=1
            NSMutableString *post = [NSString stringWithFormat:@"sMemberID=%@",[tmpDict objectForKey:memberid]];
            
            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
            
            NSURL *url = [NSURL URLWithString:@"https://www.thaicreate.com/url/deleteData.php"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                            timeoutInterval:10.0];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];
            
            NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            // Loading...
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
            
            loading = [[UIAlertView alloc] initWithTitle:@"" message:@"Deleting..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
            progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
            [loading addSubview:progress];
            [progress startAnimating];
            [progress release];
            [loading show];
            
            // Delete Object Row
            [myObject removeObjectAtIndex:indexPath.row];
            
            if (theConnection) {
                self.receivedData = nil;
            } else {
                UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"NSURLConnection " message:@"Failed in viewDidLoad"  delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                [connectFailMessage show];
                [connectFailMessage release];
            }
            
        }
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [myTable release];
    [itemEdit release];
    [super dealloc];
}

@end

สำหรับ Code อาจจะเยอะหน่อย แต่ถ้าไล่ดูแล้ว มันเป็นการ Apply จากบทความก่อน ๆ หน้านี้ทั้งสิ้น




Screenshot

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

กำลังโหลดข้อมูลจาก Web Server

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

ให้คลิกที่ Edit เพื่อลบข้อมูล

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

กำลังลบข้อมูล ซึ่งทั้งหมดนี้ได้ใช้ Progress ควบคุมการทำงาน

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

กรณีที่ลบข้อมูลเรียบร้อย ก็จะแสดงสถานะให้ทราบ

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

หรือจะ Swipe ใน Cell เพื่อลบข้อมูลก็ได้เช่นเดียวกัน

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

ลบข้อมูลเรียบร้อย

iOS/iPhone Delete Remove Data on Web Server (URL,Website)

เมื่อกลับไปดูที่ Database บน Web Server ของ MySQL Database ข้อมูลก็จะถูกลบ Delete ทิ้งไปแล้ว


.

   
Share


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


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


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-12-13 12:27:44 / 2017-03-26 08:52:44
  Download : Download  iOS/iPhone Delete Remove Data on Web Server (URL,Website)
 Sponsored Links / Related

 
iOS/iPhone Collection View and Master Detail (Objective-C, iPhone, iPad)
Rating :

 
iOS/iPhone Page Control (UIPageControl) and ScrollView (UIScrollView) (iPhone, iPad)
Rating :

 
iOS/iPhone Hide Input Keyboard and Validate Text Field (Password, Number, URL, E-Mail, Phone Number)
Rating :

 
iOS/iPhone AD BannerView (iAd Framework)
Rating :

 
iOS/iPhone Table View Show Enable Edit / Delete Cell (Swipe To Delete) (UITableView)
Rating :

 
iOS/iPhone Search Data from Web Server (URL,Website)
Rating :

 
iOS/iPhone Edit Update Data on Web Server (URL,Website)
Rating :

 
iOS/iPhone Register Form and Send Data to Web Server (PHP & MySQL)
Rating :

 
iOS/iPhone Login Username and Password from Web Server (PHP & MySQL)
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 01
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 อัตราราคา คลิกที่นี่