gpt4 book ai didi

php - 使用iOS前端将空白数据插入MYSQL数据库

转载 作者:行者123 更新时间:2023-11-30 01:18:37 24 4
gpt4 key购买 nike

我正在创建一个应用程序,需要将一行插入 mysql 数据库(在线托管),但是每当我尝试插入数据时,数据都是空白的。 php 没有任何问题,因为我的 Web 前端与 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 有关?

最佳答案

也许 PHP 没有解析请求正文,因为您还没有设置 Content-Type 请求 header :

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

另一方面,我建议您使用iOS的HTTP库,例如AFNetworking因此您不必担心手动生成请求正文。查看its documentation .

关于php - 使用iOS前端将空白数据插入MYSQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18807167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com