我试图将数据从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 */
?>
我还将网址结尾更改为"?name=test@test.com",这确实通过了。那么我应该使用什么正确的 url 脚本来发布我的名字变量呢?
任何帮助都非常感谢。
非常感谢!
$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 时才与数据库交互。
我现在使用AFNetworker类,现在应用程序,php和mysql可以很好地相互交流。
谢谢