2016-02-02 45 views
1

請幫我解決一個問題。我浪費了很多時間,但仍然無法找到什麼錯誤。objective C.通過POST方法更新mySQL數據庫

在Web上有一個名爲「c3chickens」的mySql數據庫。它有1個表「雞」,幷包含3行:id,暱稱和分數。 我的應用程序連接到數據庫,讀取和分析數據並顯示結果。它工作正常。

但我還需要在數據庫列中編寫新的暱稱和分數。下面是在Xcode此操作代碼:

NSDictionary *jsonElementToServer = [[NSDictionary alloc] initWithObjectsAndKeys:login, @"login", bestScore, @"score", nil]; 
    NSLog(@"score %@", [jsonElementToServer description]); 
    NSError* err = nil; 
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonElementToServer options:0 error:&err];  
    NSString *url = @"http://chickens.gol.com/php.php"; 
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] 
                  cachePolicy:NSURLRequestUseProtocolCachePolicy 
                 timeoutInterval:60.0f]; 
    NSMutableData *body = [NSMutableData data]; 
    [body appendData:jsonData]; 
    [theRequest setHTTPBody:body]; 
    [theRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [theRequest setHTTPMethod:@"POST"]; 

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:theRequest delegate:self]; 
    if (connection) { 
     NSLog(@"connect"); 
     self.infoData = [NSMutableData data]; 
    } else { 
     NSLog(@"Connection failed"); 
    } 

,這裏是我的php.php文件:

<?php 
$username = "..."; 
$password = "..."; 
$hostname = "localhost"; 
$dbnamemysql = "c3chickens"; 
$mysqli = new mysqli($hostname, $username, $password, $dbnamemysql); 

if(!$mysqli){ 
    exit("ERROR DB"); 
    $result = "NO METHOD"; 

}else{ 
    mysql_select_db('c3chickens'); 
    mysql_query("INSERT INTO chickens ('nickname', 'score') VALUES (null, null, '". 
    mysql_real_escape_string($_REQUEST['login']). 
    "', '". 
    mysql_real_escape_string($_REQUEST['score']). 
    "')"); 
    $result = $mysqli->query($query); 
} 
?> 

之前我沒有使用PHP,所以我不`噸瞭解這種語言。我在互聯網上閱讀例子,並嘗試了很多變種的這個PHP文件,但沒有結果。我懷疑我錯過了一些重要和簡單的細節。

+0

加入你的雞表的圖像。所以我們可以對列有適當的想法。 –

+0

檢查更新後的答案。 –

回答

0

千萬不要混合mysql with mysqli

寫下你的php代碼如下。

// Connection object 
$con = mysqli_connect($hostname, $username, $password, $dbnamemysql) or die("Some error occurred during connection " . mysqli_error($con)); 
// Get data in variables. Here use mysqli_real_escape_string 
$login = mysqli_real_escape_string($con, $_REQUEST['login']); 
$score = mysqli_real_escape_string($con, $_REQUEST['score']); 
// Query execution 
$result = mysqli_query($con , "INSERT INTO chickens('nickname', 'score') VALUES('$login', '$score')"); 
// $result will return true or false 
if($result){ 
    echo 'success'; 
}else{ 
    echo("Error description: " . mysqli_error($con)); 
} 

下面寫兩行文件的起點: -

// It will show all php warning, notice, and errors. 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 

希望它會幫助你:)

+0

結果是「失敗」 –

+0

什麼是錯誤?您的錯誤報告是否打開? –

+0

錯誤是「注意:未定義的索引:登錄在/var/www/clients/client3/web21/web/php.php 26行」。所以它看不到登錄,從xcode添加。 –