开发者

How do I use Objective-c to connect to my php/MySQL server?

开发者 https://www.devze.com 2023-02-19 06:30 出处:网络
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:

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 t开发者_JAVA百科his 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号