简体   繁体   中英

How To Send “chat message” From iOS TextField To A Remote Database

so I am trying to create a simple iOS program where I can save a chat message to a remote MySQL server and then load it back.

My app has textbox where I can enter in data and a button to save the data to an external database.

My php file looks like this:

<?php

$DB_HostName = "hostname";
$DB_Name = "dbname";
$DB_User = "dbuser";
$DB_Pass = "dbpass";
$DB_Table = "dbtable";

if (isset ($_GET["name"]))
    $name = $_GET["name"];
else
    //$name = "Ghalia";
    echo ('Please enter a name');

$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); 
mysql_select_db($DB_Name,$con) or die(mysql_error()); 

$sql = "insert into $DB_Table (name) values('$name');";
$res = mysql_query($sql,$con) or die(mysql_error());

mysql_close($con);
if ($res) {
    echo "success";
}else{
    echo "faild";
}
?>

My ViewController.h file looks like this:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize txtName;

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

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

- (IBAction)insert:(id)sender {
//create string contains url address for php file, the file name is phpfile.php, it receives a     parameter :name

NSString *strURL = [NSString stringWithFormat:@"http://xxdsadxx.net/phpFile.php?name=%@", txtName.text];

//to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
//to receive the returned value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];

NSLog(@"%@", strResult);

}
@end

Right now, I have it coded to only store names.

I want to store a chat message like "hello, how are you?", the string will not store properly to the external server. Any idea how I can achieve this? Thanks.

You should not use dataWithContentsOfURL. That is a blocking call. It will freeze the UI until the network request complete. You want to do an HTTP get using NSURLConnection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM