douyun1972 2011-03-24 15:02
浏览 70
已采纳

如何使用Objective-c连接到我的php / MySQL服务器?

I have a MySQL database/table set up and a .php file online that inserts data into the mysql database. My php code is here:

<?

$name = $_GET['name'];
$minScore = $_GET['minScore'];
$hourScore = $_GET['hourScore'];
$dayScore = $_GET['dayScore'];

$service = "dddd.com";
$username = "dddd";
$password = "dddd";
$database = "dddd_DATA1";

mysql_connect($service, $username, $password);
@mysql_select_db($database) or die( "Unable to select database");

if($minScore>0) {
    $query="INSERT INTO currentScores VALUES ('$name', '$minScore', '$hourScore','$dayScore',null)";
    $result=mysql_query($query);
    echo("Score submitted! Name: $name, Score: $minScore");
}
else {
echo("No score was submitted");
}

?>

It works the way I want it to typing a URL link like this right in a browser: http://dddd.com/sendScores.php?name=NAMEYNAME&minScore=22&hourScore=3&dayScore=1

What I want to do now is somehow send this from my iPhone objective-c app. I assume I need to use NSURLRequests and NSURLConnections but I have been unable to get it to work so far. How can I do this? and if you have time... any ideas on how to get the info from the database back onto my app? Would I need to convert it to xml (or maybe a .plist) using php and then use an xml parser in objective-c? Thank you for your time.

  • 写回答

1条回答 默认 最新

  • duanlian1978 2011-03-24 15:12
    关注

    I suggest using the ASIHTTPFramework which makes requesting URLs much easier. To provide a simple example with NSURLRequest you can do a synchronous request:

    NSError * error = nil;
    NSURLResponse * response = nil;
    NSData * downloadedData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]] 
                                                    returningResponse:&response 
                                                                error:&error];
    

    downloadedData contains the response body of the request, so the app received data you send along.

    It is not recommended to use synchronous requests, cause they block your whole app.

    The format to choose to send back data depends on the complexity. Use plain text if you just want to return a status code or some string. If you like to get a structured response with error code and an array or whatever, I suggest using JSON. XML is nice as well but using XMLParsers in iOS can be a pain. There are nice libraries to parse JSON, which is transformed to NSDictionaries and NSArrays and can therefore be easily used in your app.

    I frequently make use of the json-framork

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码