iOS no communication between iPhone app and MySQL

2019-09-15 05:38发布

I need help trying to figure out why my iPhone app is not communicating with my PHP. I have a text field where the user can enter a message and there is a button that is supposed to tell the app when the text has been entered and needs to be posted to my mySQL database.

My PHP and iOS code are pasted below, but I also included some debugging statements here.

I put a break at the line if([serverOutput...) and at that point I get the following:

alertsuccess    UIAlertView *   0x00000000
dataURL NSData *    0x00000000 
messageString   __NSCFString *  0x0685e7a0 @"hi"
serverOutput    __NSCFConstantString *  0x00b75a7c
url NSURL * 0x06869540 @"http://www.mysite.com/connect.php?message=hi"

From the debug breakpoint, I would expect serverOutput to say "OK" but it's blank, which I believe means that it did not connect with my PHP. Your help is appreciated on how to fix this.

<?php
// Connecting, selecting database
$link = mysql_connect("localhost", "user", "password")
or die('Could not connect: ' . mysql_error());

mysql_select_db("mydb") or die('Could not select database');

// Performing SQL query
$query = "INSERT INTO messages (message,date) VALUES ('$_GET["message"]',NOW())";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

echo "OK";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

iPhone code

- (IBAction)postmessage:(id)sender {

self.message = self.messageField.text;
NSString *messageString = self.message;
UIAlertView *alertsuccess;

 //construct an URL for your script, containing the encoded text for parameter value
NSURL* url = [NSURL URLWithString:
 [NSString stringWithFormat:
 @"http://www.mysite.com/connect.php?message=%@",messageString]];

NSData *dataURL =  [NSData dataWithContentsOfURL:url];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];

if([serverOutput isEqualToString:@"OK"]) {

   alertsuccess = [[UIAlertView alloc] initWithTitle:@"Posted" message:@"Done"
                                                          delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

} else {
    alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Done"
                                                          delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

}
[alertsuccess show];

}

1条回答
贼婆χ
2楼-- · 2019-09-15 06:15

Error is here $query = "INSERT INTO messages (message,date) VALUES ('$_GET["message"]',NOW())";

Should be

$query = "INSERT INTO messages (message,date) VALUES ('" . $_GET["message"] . "', NOW())";

or

$query = "INSERT INTO messages (message,date) VALUES ('${_GET["message"]}', NOW())";
查看更多
登录 后发表回答