使用iOS前端插入MYSQL数据库的空白数据

时间:2013-09-14 22:47:08

标签: php mysql ios

我正在创建一个应用程序,需要在mysql数据库中插入一行(在线托管),但每当我尝试插入数据时,数据都是空白的。由于我的网络前端与php脚本完美配合,因此php没有任何问题。

NSString *user = self.registerUsername.text;
NSString *password = self.registerPassword.text;
NSString *email = self.registerEmail.text;
NSString *model = [NSString stringWithFormat:@"%@", [[UIDevice currentDevice] model]];
NSString *sysVer = [NSString stringWithFormat:@"%@", [[UIDevice currentDevice] systemVersion]];

NSString *connectionURL = @"mydomain.com/Register.php";
NSLog(@"%@", connectionURL);
//this is logged correctly

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:connectionURL]];
[request setHTTPMethod:@"POST"];

NSString *insert = [[NSString alloc] initWithFormat:@"username=%@&password=%@&email=%@&model=%@&sysver=%@", user, password, email, model, sysVer];

NSLog(@"%@", insert);
[request setHTTPBody:[insert dataUsingEncoding:NSASCIIStringEncoding]];
//This is also logged correctly, giving me the right format i would expect

NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request                             returningResponse:&response error:&error];

NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(@"%@", responseString);
//The response string is also correct, but no data is inserted into the database

NSString *success = @"success";
[success dataUsingEncoding:NSUTF8StringEncoding];

NSLog(@"%lu", (unsigned long)responseString.length);
NSLog(@"%lu", (unsigned long)success.length);

mRegister.php

<?php

header('Content-type: text/plain; charset=utf-8');

include("config/dp.php"); //<- db connection

$con = mysql_connect("127.0.0.1","user","pass");
if(! $con)
{
die('Connection Failed'.mysql_error());
}

mysql_select_db("hk", $con);

$message = "";

$username = ($_POST['username']); 
$password = ($_POST['password']);
$email = ($_POST['email']);
$model = ($_POST['model']);
$sysver = ($_POST['sysver']);

$submit = $_POST["registerform"];

$sql = "INSERT INTO members (`username`, `password`, `email`, `model`, `sysver`) VALUES ('$username', '$password', '$email', '$model', '$sysver')";
$result = mysql_query($sql);

$row = mysql_fetch_array($result);

if ($result) { $message = "success"; }
else { $message = "failed"; }

echo utf8_encode($message);

?> 

此外,responseString通常会显示一些奇怪的字符,因此会影响responseString.length值。我的代码有问题还是与我的PHP有关?

1 个答案:

答案 0 :(得分:0)

也许PHP没有解析请求正文,因为你没有设置Content-Type请求标题:

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

另一方面,我建议您使用iOS的HTTP库,例如AFNetworking,这样您就不必担心手动生成请求体。查看its documentation