【问题标题】:Send MySQL records to iOS via PHP通过 PHP 将 MySQL 记录发送到 iOS
【发布时间】:2012-05-30 08:29:49
【问题描述】:

每个人。

我正在使用通过 PHP 连接到 MySQL 的 iOS 应用程序。

我希望我的应用程序发送 PHP GET 请求并从 MySQL 数据库中选择一些数据,但我不知道如何将 MySQL 上的数据发送到 iOS。这是我的代码。

myDataGetter.m

//create a request and connect (url is my PHP file's)
NSURLRequest* getRequest = [NSURLRequest requestWithURL:url];
NSURLConnection* connection = [NSURLConnection connectionWithRequest:getRequest      
                                                            delegate:self];
if (connection) {
    //data received from PHP will be stored in receivedData
    receivedData = [[NSMutableData alloc] init];
} else {
    //error
}

在 myDataGetter.m 中,我设置了 NSURLConnection 的委托方法。例如,

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0]
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

在我的 PHP 文件中,

$con = mysql_connect ('host', 'user', 'pass');
mysql_select_db ('dbname', $con);

$rows = mysql_query ("SELECT name, age, email FROM table");
while ($row = mysql_fetch_array ($rows)) {
    $name = $row["name"];
    $age = $row["age"];
    $email = $row["email"];
}

在本例中,我想向 iOS 发送 $name、$age 和 $email。如果你知道怎么做,请帮助我。

谢谢。

【问题讨论】:

  • U 在哪里创建 iPhone 与 PHP 服务器的连接?
  • @Sergey 感谢您的评论!我在 myDataGetter.m 中编写了连接,它是 UIViewController 的子类。在同一个 ViewController 中,我创建并添加了 addSubView:一个 UIButton,当我按下它时,连接将开始。

标签: php mysql ios http nsurlconnection


【解决方案1】:

我总是使用 ASIHTTPRequest 来完成这类工作。它比 NSURLConnection 框架强大得多。

其次,我会使用 PHP 将结果编码为 JSON,然后使用非常好的 iOS SBJson 框架将请求的结果简单地放入 NSDictionary 或 NSMutableArray。

http://allseeing-i.com/ASIHTTPRequest/Setup-instructions

http://stig.github.com/json-framework/

JSON encode MySQL results

【讨论】:

  • 他们看起来很不错。感谢您的帮助!
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多