【问题标题】:how to read an external mysql database如何读取外部mysql数据库
【发布时间】:2026-02-03 10:05:03
【问题描述】:

我正在尝试查找如何在我的 iphone 应用程序中从我的数据库中读取数据。数据库在我的服务器中,我尝试的方法类似于我在 Android 中的操作方式(我不确定是否是最好的方法):

NSString *hostStr = @"http://www.myip/notices.php";


NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];    
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];

NSLog(@"Mysql response:is %@",serverOutput);

我得到的是“Mysql 响应:是数组”,什么是真的:

<?php
mysql_connect("localhost","user","pass");
mysql_select_db("database");


  $q = mysql_query("SELECT id, title FROM jos_content WHERE catid=12 AND state=1 AND DATE(publish_up) <= NOW() ORDER BY DATE(publish_up) DESC");

   while($e=mysql_fetch_assoc($q))

    $output[]=array("id" => $e['id'], "title" =>  utf8_encode($e['title']));
        echo $e;

print($output);

mysql_close();


?>

我该怎么做?

提前谢谢你

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    从您的 php 将数据打印为 JSON,这样处理起来会容易得多

    在你的 PHP 中使用

    而不是

    print($output);
    

    使用

    echo json_encode($output);
    

    然后在你的 iOS 应用中你可以使用this framewrok

    其他资源

    要使用 SBJSon,您需要执行以下操作

    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
    id object = [serverOutput JSONValue];
    NSMutableDictionary *dictionary = (NSMutableDictionary *)object;
    

    现在dictionary 将包含值和键的字典

    【讨论】:

    • 谢谢,我很缺乏经验。我该如何使用该框架?谢谢!
    • 谢谢,但我想做的是将框架添加到我的项目中。 github.com/stig/json-framework/blob/master/INSTALL.md 但是在第三步中,我应该在哪里添加类文件?
    • 新提示... NSLog(@"serverOutput %@", serverOutput); NSLog(@"字典 %@", 字典);都一样,怎么可能?
    • @user1256477 抱歉,我的代码有错误,请检查更新后的答案