【问题标题】:POST data iOS app to php to mysqlPOST 数据 iOS 应用程序到 php 到 mysql
【发布时间】:2023-03-09 11:27:01
【问题描述】:

我正在尝试将数据从 iOS 应用 SQLite 数据库发布到存储在服务器上的 php 文件。

错误告诉我我有一个未定义的变量。

这是我的 iOS 应用代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

// Override point for customization after application launch.

    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *path = [docsPath stringByAppendingPathComponent:@"database.sqlite"];

    FMDatabase* database = [FMDatabase databaseWithPath:path];
    [database open];
    [database executeUpdate:@"create table user(name text primary key, age int)"];

// Building the string ourself

    NSString *query = [NSString stringWithFormat:@"insert into user values ('%@', %d)",@"brandontreb", 25];
    [database executeUpdate:query];

// Fetch all users

    FMResultSet *results = [database executeQuery:@"select * from user"];
    while([results next]) {
    NSString *name = [results stringForColumn:@"name"];
    NSInteger age  = [results intForColumn:@"age"];        
    NSLog(@"User: %@ - %ld",name, (long)age);


    NSURL *url = [NSURL URLWithString:@"http://urldetails/insertMySQL.php?var=name"];
    NSString *postData = [NSString stringWithFormat:@"%@",name];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]
                                    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    //[self startConnection:(NSMutableURLRequest *)request];

    self.urlConnection = [NSURLConnection connectionWithRequest:request delegate:self];
    if([self.result isEqualToString:@"New Alert"])
    {
        name = @"Scuess";
    }
}

//[database executeUpdate:@"delete from user where age = 25"];

[database close];

return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    if (self.receivedData) {
    self.receivedData = nil;
    }
    self.receivedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.receivedData appendData:data];
    }

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"receivedData: %@", [[NSString alloc] initWithData:self.receivedData  encoding:NSUTF8StringEncoding]);
    self.urlConnection = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"requesting error: %@", [error localizedDescription]);
    self.urlConnection = nil;
}

我的php文件是这样的:

<?php

//CONNECT TO MYSQL DATABASE - ADD YOUR DATABASE DETAILS HERE

$db = new PDO( 'mysql:host=;dbname=', '', '' );

if(isset($_POST['name'])){
$app_name = $_POST['name'];
}

try {
$sql = "INSERT INTO users (id,name) VALUES (:id,:app_name)";
 $query = $db->prepare( $sql );
 $query->execute(array(':id'=>NULL,':app_name'=>$name));

 } catch (Exception $e) {
die("There's an error in the query!");
}

?>

编辑

php 文件正在运行,但没有任何内容输入到 mysql 中。

作为测试,我将我的 php 代码更改为以下内容:

<?php

//CONNECT TO MYSQL DATABASE - ADD YOUR DATABASE DETAILS HERE

if(isset($_REQUEST['name'])){
$app_name = $_REQUEST['name'];
/* removed } here... */

try {
$db = new PDO( 'mysql:host=;dbname=', 'root', '' );
$sql = "INSERT INTO user (id,name) VALUES (:id,:app_name)";
$query = $db->prepare( $sql );
$query->execute(array(':id'=>NULL,':app_name'=>$app_name));

} catch (Exception $e) {
die("There's an error in the query!");
}
} /* and placed it here */

?>

我还将 url 结尾更改为“?name=test@test.com”并且确实成功了。那么我应该使用什么正确的 url 脚本来发布我的 name 变量?

非常感谢任何帮助。

非常感谢!

【问题讨论】:

    标签: php ios objective-c xcode sqlite


    【解决方案1】:
     $query->execute(array(':id'=>NULL,':app_name'=>$name));
    

    错了,你的变量叫$app_name,而不是$name

    您应该考虑将整个代码放在 if 语句中:

    if(isset($_POST['name'])){
    $app_name = $_POST['name'];
    /* removed } here... */
    
    try {
    $db = new PDO( 'mysql:host=;dbname=', '', '' );
    $sql = "INSERT INTO users (id,name) VALUES (:id,:app_name)";
     $query = $db->prepare( $sql );
     $query->execute(array(':id'=>NULL,':app_name'=>$name));
    
     } catch (Exception $e) {
    die("There's an error in the query!");
    }
    } /* and placed it here */
    

    这将确保您仅在实际设置了 $_POST 时才与数据库交互。

    【讨论】:

    • 太棒了,错误消失了。我检查了mysql,但没有数据通过,有什么想法吗?
    【解决方案2】:

    我现在改用 AFNetworking 类,现在应用程序、php 和 mysql 可以很好地相互交流。

    谢谢

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 2017-05-06
      • 2011-05-16
      • 2012-12-15
      相关资源
      最近更新 更多