Thursday, August 23, 2012

How to save Arabic Data from iPhone to PHP Server

How to save Arabic Data from iPhone to PHP Server?

I am writing here to explain how we can store Arabic content from iPad/iPhone on to the web server and how to retrieve it. Some of us might be knowing but when I searched, I was not able to found a perfect solution for it. 

There is not a complete solution that display how to write PHP web services along with the iOS code for it.

No more talks further, lets do it :) 

Getting Started

Steps to follow:
1. Download and install XAMPP for mac.
2. Creating the database and tables to store the content.
3. Writing web services to save and retrieve data from database.
4. Writing the code in Xcode

Step 1: Download and install XAMPP for mac.

Firstly, download the XAMPP for MAC and install the DMG. You can download it from here: XAMPP for MAC

Open the DMG: 

Drag XAMPP folder to Applications

Open the XAMPP from Spotlight:

Click on XAMPP Control and it will open. Now start the Apache and MySQL. It will ask you a password. Enter your OS password if any.

Now First thing is to check that all is done. So lets check whether XAMPP is correctly installed or not.

Open the Safari Browser and in the Address Bar type the URL: http://localhost
The XAMPP browser page would be displayed:

This completes the Step 1.

Step 2: Creating the database and tables to store the content.

Click on PHPMyAdmin link in the left bar of the XAMPP webpage:

Give a name to the database as you required. I am giving as TestArabic. 

Note: Change the collation to "utf8_unicode_ci". This is very important as we need to store the Arabic Content and that can only be saved if the collation is "utf8". 

Click on Create button and the database would be created and displayed on left side bar:

Next is to Create the table in the database. Lets do it right away. 

I hope you are not getting bored.

In the above picture you will find the fields to create the table. Give a name to the table with number of fields. For now, I am giving the name of table as TestTable with 3 fields: ID, name and address

Also set the collation.

Click on Go

Fill in all the details as shown below, and Click on Save.

All set now is the time to do some coding part. Lets create WebService in PHP to save and get the data from the table.

Step 3: Writing web services to Save and Retrieve Data from Database

First web service would be to Save the Data from iPhone to the Database. For that, I will be creating one PHP web service and then will write code in Xcode to save the data.

1. Create a web service to Save it in Database
a. Open TextWrangler in Mac. If you don't have it, download it as it is free. Do not write the Web Service PHP code in Text Edit. It doesn't save properly in PHP. or you can also write the code in Xcode. 

Copy the script below and paste it in the Text Wrangler or in Xcode, which ever you are using, and save it in folder "/Applications/XAMPP/xamppfiles/htdocs/TestArabic"

Create the folder named TestArabic and save the file in it.


$name = $_POST['name'] or die('Invalid name for request. '); //1
$address = $_POST['address'] or die('Invalid address for request. '); //2

$conn = mysql_connect('localhost','root','') or die('Cannot connect to the DB'); //3

mysql_select_db('TestArabic',$conn) or die('Cannot select the DB'); //4
mysql_query("SET NAMES 'utf8'"); //5

$query = 'INSERT into TestTable(Name,Address) values(\''.$name.'\' ,\''.$address.'\')'; //6

$result = mysql_query($query,$conn) or die('Errant query:  '.$query); //7

if(!$result){ //8
echo "Request Failed". mysql_error(); //9
echo "Request Success"; //10

@mysql_close($conn); //11

Lets understand the script for now:

//1: Get the value of the parameter name that we are going to send from Xcode.
//2: Get the value of the parameter address that we are going to send from Xcode.
//3: mysql_connect is used to connect the localhost with root as the username and if there is password, specify in the third parameter.
//4: mysql_select_db is used to connect the Table from the connection.
//5: This is the important line which set the query as 'utf8' else it will not save the data in Arabic.
//6: Next is the Insert query where in we pass the two column names and giving the values for it.
//7: mysql_query takes 2 parameters where in we pass the query created and the connection.
//8: Check the result, if the result is false i.e. insertion is failed, then the request is failed
//9: Print the mysql_error() so that we can display it on iPhone.
//10: If the result is true then insertion is successful and send the response.
//11: Close the connection

2. Write Code in Xcode and test the web service on iPhone.
1. Open Xcode, and Create a new project and choose Single View Application, Click Next.

2.a) Give a Product Name as TestingArabic.
2.b) Check the box "Use Storyboards".
2.c) Give a Company Identifier what ever you feel.
2.d) Give a class prefix as per your convenience. I have chosen JS as my name initials.
Click Next and save the project.

3. Open Storyboard file and add two UITextFields, one for Name and other for Address. Add a UIActivityIndicatorView and a button to Submit the request.

4. Click on Editor on the Menu and Embed In -> Navigation Controller.
5. Add ASIRequest classes, and Reachability classes, that will help in requesting the web service easily.
6. Now Click on the project Name, Click on Target - TestingArabic and click on the Build Phases, Expand the Link Binary With Libraries, and Add the frameworks-> MobileCoreServices, SystemConfiguration, CFNetwork and libz.dylib.

7. Here is the JSViewController.h code:

@interface JSViewController : UIViewController

@property (retain, nonatomic) IBOutlet UITextField *txtName;
@property (retain, nonatomic) IBOutlet UITextField *txtAdress;
@property (retain, nonatomic) IBOutlet UIActivityIndicatorView *requestIndicator;
- (IBAction)btnSubmitClicked:(UIButton *)sender;

8. Here is the JSViewController.m code:

#import "JSViewController.h"

#import "ASIFormDataRequest.h"

@interface JSViewController ()


@implementation JSViewController
@synthesize txtName;
@synthesize txtAdress;
@synthesize requestIndicator;

- (void)viewDidLoad
    [super viewDidLoad];
    [requestIndicator setHidden:YES];
    [requestIndicator setHidesWhenStopped:YES];
// Do any additional setup after loading the view, typically from a nib.

- (void)viewDidUnload
    [self setTxtName:nil];
    [self setTxtAdress:nil];
    [self setRequestIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);

- (void)dealloc {
    [txtName release];
    [txtAdress release];
    [requestIndicator release];
    [super dealloc];
- (IBAction)btnSubmitClicked:(UIButton *)sender {
    [requestIndicator setHidden:NO];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/TestArabic/insert.php"]];
    [request setRequestMethod:@"POST"];
    [request setPostValue:txtName.text forKey:@"name"];
    [request setPostValue:txtAdress.text forKey:@"address"];
    [request setDidFailSelector:@selector(requestFailed:)];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request setDelegate:self];
    [request startAsynchronous];
    [request release];
    [txtName resignFirstResponder];
    [txtAdress resignFirstResponder];

-(void)requestFailed:(ASIFormDataRequest *)request{
    [requestIndicator stopAnimating];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:[request.error localizedDescription] delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert show];
    [alert release];


-(void)requestFinished:(ASIFormDataRequest *)request{
    [requestIndicator stopAnimating];
    NSLog(@"req %@",request.responseString);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:request.responseString delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert show];
    [alert release];

9. Copy and paste the code and Build and Run:
10. You will not be able to enter the Arabic content in the name and address field as there is no Arabic Keyboard set up in iPhone Simulator.
11. To install the Arabic Keyboard in iPhone Simulator, Open the iPhone Simulator, Go to Settings->General->Keyboard->International Keyboards->Add New Keyboard..-> Arabic
12. Now again Build and Run the application.

13. Change the keyboard and enter the arabic content, and click Submit.

14. You will get the Success message.

You can download the project from here.

Please post your comments if you found it useful. I will write the next code to get the Arabic content from the Database and display it on iPhone.


  1. Fantastic Tutorial i was in search of such nice tutorial n Jassi helped me alot in doing my application.Thanks alot

  2. i have 3 language in english,urdu and arabic i have create on database in three language but i have fetch the database in xcode then urdu and arabic language are not didsplay in proper language pls ans me fast..
    error-azkar_arabic" = "\U0645\U0633\U062c\U062f \U0627\U0644\U0623\U0630\U0643\U0627\U0631";
    this are display in arabic language

  3. Have you implemented as per my tutorial. I have explained everything in detail. Please try again and let me know if you face issue again.