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 NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView) บทความนี้จะเป็นการ Apply ใช้ NSURLConnection กับการเชื่อมต่อข้อมูลของ MySQL Database ที่ถูกจัดเก็บไว้บน Web Server โดยใช้ php ทำหน้าที่ในการอ่านข้อมูลจาก MySQL แล้งแปลงเป็น JSON เพื่อจะรอ Client เข้าไปทำการ Request ข้อมูลผ่าน URL (Webiste) ที่มีนามสกุล .php โดยในตัวอย่างนี้เราจะได้เรียนรู้และ Apply การใช้งานอยู่ 3-4 ตัวเช่น NSURLConnection , PHP MySQL และการใช้ JSON Parser และการนำข้อมูลเหล่านั้นแสดงผลบน Table View (UITableView)

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)


และเพื่อความเข้าใจในบทความนี้ อยากจะแนะนำให้อ่านบทความต่าง ๆ เหล่านี้ที่เกี่ยวข้อง เช่น NSURLConnection , JSON Parser , และ Table View แต่ถ้าเข้าใจแล้วก็สามารถข้ามบทความเหล่านั้นได้เลย

iOS/iPhone NSURLConnection (Objective-C)

iOS/iPhone and JSON (Create JSON and JSON Parsing , Objective-C)

iOS/iPhone Display Image on Table View from JSON URL (Web Site)


Example ตัวอย่างการใช้ NSURLConnection และ PHP MySQL / JSON (TableView,UITableView)

MySQL Database
CREATE TABLE `gallery` (
  `GalleryID` int(3) NOT NULL auto_increment,
  `Name` varchar(50) NOT NULL,
  `TitleName` varchar(150) NOT NULL,
  `Thumbnail` varchar(100) NOT NULL,
  PRIMARY KEY  (`GalleryID`)
) ENGINE=MyISAM  AUTO_INCREMENT=5 ;

-- 
-- Dumping data for table `gallery`
-- 

INSERT INTO `gallery` VALUES (1, 'Name 1', 'The my gallery title 1', 'https://www.thaicreate.com/url/girl1.jpg');
INSERT INTO `gallery` VALUES (2, 'Name 2', 'The my gallery title 2', 'https://www.thaicreate.com/url/girl2.jpg');
INSERT INTO `gallery` VALUES (3, 'Name 3', 'The my gallery title 3', 'https://www.thaicreate.com/url/girl3.jpg');
INSERT INTO `gallery` VALUES (4, 'Name 4', 'The my gallery title 4', 'https://www.thaicreate.com/url/girl4.jpg');

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

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

getGallery.php
<?php
	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");
	$strSQL = "SELECT * FROM gallery 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);
?>

ไฟล์ php สำหรับอ่านข้อมูลจาก MySQL และแปลงให้เป็น JSON








iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

เมื่อเรียกไฟล์ php ผ่าน URL ของ Web Browser

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

ตัวอย่างนี้จะแสดงรูปภาพด้วย และทดสอบการเรียกรูปภาพผ่าน Web Browser

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

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

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

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

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

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

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

ลาก Table View (UITableView) มาวางไว้บนหน้าจอ

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

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

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

ใน Class ของ .h ให้เชื่อม IBOutlet ให้เรียบร้อย จากนั้นให้เขียน Code ของ Objective-C ทั้งหมดดังนี้

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

#import <UIKit/UIKit.h>

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

@property(nonatomic,assign) NSMutableData *receivedData;

@end


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

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *myObject;
    
    // A dictionary object
    NSDictionary *dict;
    
    // Define keys
    NSString *galleryid;
    NSString *name;
    NSString *titlename;
    NSString *thumbnail;
}

@end

@implementation ViewController

@synthesize receivedData;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view, typically from a nib.
    
    // Define keys
    galleryid = @"GalleryID";
    name = @"Name";
    titlename = @"TitleName";
    thumbnail = @"Thumbnail";
    
    // Create array to hold dictionaries
    myObject = [[NSMutableArray alloc] init];
    
    
    NSURLRequest *theRequest =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.thaicreate.com/url/getGallery.php"]
                     cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                 timeoutInterval:10.0];
    
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    
    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)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    receivedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [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
{
    if(receivedData)
    {
        //NSLog(@"%@",receivedData);
        //NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
        //NSLog(@"%@",dataString);
        
        id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
        
        // values in foreach loop
        for (NSDictionary *dataDict in jsonObjects) {
            NSString *strGalleryID = [dataDict objectForKey:@"GalleryID"];
            NSString *strName = [dataDict objectForKey:@"Name"];
            NSString *strTitleName = [dataDict objectForKey:@"TitleName"];
            NSString *strThumbnail = [dataDict objectForKey:@"Thumbnail"];
            
            dict = [NSDictionary dictionaryWithObjectsAndKeys:
                    strGalleryID, galleryid,
                    strName, name,
                    strTitleName, titlename,
                    strThumbnail, thumbnail,
                    nil];
            [myObject addObject:dict];
        }
    
        [myTable reloadData];
    }
    
    
    // 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
{
    
    int nbCount = [myObject count];
    
    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];
    }
    
    if (nbCount ==0)
        cell.textLabel.text = @"Loading Data";
    else
    {
        NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
        
        NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [[UIImage alloc] initWithData:data];
        cell.imageView.image = img;
        
        cell.textLabel.text = [tmpDict objectForKey:name];
        cell.detailTextLabel.text= [tmpDict objectForKey:titlename];
    }
    
    //[tmpDict objectForKey:galleryid]
    //[tmpDict objectForKey:name]
    //[tmpDict objectForKey:titlename]
    //[tmpDict objectForKey:thumbnail]
    
    return cell;
}



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

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









Screenshot

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)

แสดงข้อมูลบน Table View ซึ่งอ่านมาจาก URL ทำงานด้วย PHP กับ MySQL ผ่าน Class ของ NSURLConnection

   
Share


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


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


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-12-13 09:49:21 / 2017-03-26 08:57:24
  Download : Download  iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)
 Sponsored Links / Related

 
iOS/iPhone Web View (UIWebView) Open Web Site and HTML (Objective-C, iPhone, iPad)
Rating :

 
iOS/iPhone Get the String contents from URL (Website)
Rating :

 
iOS/iPhone Image URL Display an Image from URL (Website)
Rating :

 
iOS/iPhone and JSON (Create JSON and JSON Parsing, Objective-C)
Rating :

 
iOS/iPhone Table View and JSON (UITableView from JSON Parser)
Rating :

 
iOS/iPhone Passing JSON (NSJSONSerialization) Between View
Rating :

 
iOS/iPhone PHP/MySQL and JSON Parsing (Objective-C)
Rating :

 
iOS/iPhone Display Image on Table View from JSON URL (Web Site)
Rating :

 
iOS/iPhone Search Bar (UISearchBar) Data from Web Server Using JSON
Rating :

 
iOS/iPhone Picker View and JSON (UIPickerView)
Rating :

 
iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)
Rating :

 
iOS/iPhone XML Parser / XML Feed from URL (NSXMLParser ,Objective-C)
Rating :

 
iOS/iPhone NSURLConnection (Objective-C)
Rating :

 
iOS/iPhone Image View and NSURLConnection ActivityIndicator Progress
Rating :

 
iOS/iPhone NSURLRequest Example (Objective-C)
Rating :

 
iOS/iPhone NSURLConnection POST Method and Send Parameter (Objective-C)
Rating :

 
iOS/iPhone NSMutableURLRequest Example (Objective-C)
Rating :

 
iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)
Rating :

 
iOS/iPhone Add Insert Data to Web Server (URL,Website, PHP and MySQL)
Rating :

 
iOS/iPhone Retrieve Read List Show Data from Web Server (URL,Website,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 05
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 อัตราราคา คลิกที่นี่