【问题标题】:Retrieve and use entire MYSQL Table in Swift在 Swift 中检索和使用整个 MYSQL 表
【发布时间】:2015-10-12 14:01:45
【问题描述】:

我浏览了互联网,但还没有找到一个解决方案,看起来应该是一种常见的做法。

我正在尝试用 Swift 编写一个方法,该方法使用 PHP 后端从我的数据库中的特定 MYSQL 表中检索所有数据。

在应用程序的其他部分(用户登录等)我已经有一个类似的系统工作,但这只需要为一个特定用户返回一些变量,所以我可以将这些在 JSON 数据中作为单独的变量返回并且将它们存储在 NSUserDictionary 中,以便在整个应用程序中使用,很简单!

但是现在我有另一个表格,其中包含有关不同“商店”的信息,每一行都存储各种详细信息(位置、名称等)。我希望能够将这些及其名称绘制到 MKMapView 上,因此我需要检索整个表,然后在 swift 中遍历每一行(商店)。 (嗯,这是我能想到的唯一方法)。

我的问题是我只能弄清楚如何在 PHP 中返回“一维”JSON 数据(例如,特定商店的位置/名称等),而不是整个商店阵列?

这是我在 swift 中用于为用户检索一维数据的代码:

        var post:NSString = "email=\(email)&password=\(password)"

        NSLog("PostData: %@",post);

        var url:NSURL = NSURL(string:"http://www.agentsweep.co.uk/scripts/agentsweep_user_login.php")!

        var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

        var postLength:NSString = String( postData.length )

        var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")


        var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

        if ( urlData != nil ) {
            let res = response as! NSHTTPURLResponse!;

            NSLog("Response code: %ld", res.statusCode);

            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                var error: NSError?

                let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary

这是返回它的后端 PHP 部分:

if ($result = $mysqli->query("SELECT id, fullname, mobile, mobilepref, address, autofill FROM users WHERE email = '$email';")) {
                $userData = $result->fetch_assoc();
                $result->close();
            }  

            $fullnameResult = $userData["fullname"];
            $idResult = $userData["id"];
            $mobileResult = $userData["mobile"];
            $mobilePrefResult = $userData["mobilepref"];
            $addressResult = $userData["address"];
            $autofillResult = $userData["autofill"];
            /* close connection */
            $mysqli->close();

            if ($id) {

                error_log("User $email: password match.");


                /* Reply Data:*/
                /*echo '{"success":1,"id":'. $idResult .',"fullname":'. $fullname .',"mobile":'. $mobileResult .',"mobilepref":'. $mobilePrefResult .',"address":'. $addressResult .'}';
            */
                echo '{"success":1,"idref":"'. $idResult .'","fullname":"'. $fullnameResult .'","mobile":"'. $mobileResult .'","mobilepref":"'. $mobilePrefResult .'","address":"'. $addressResult .'","autofill":"'. $autofillResult .'"}'; 

谁能给我一个关于如何处理整个表而不是一行的清晰解释?非常感谢您,将对所有有用的答案进行投票,并尽快选出最好的答案! :)

【问题讨论】:

    标签: php ios mysql json swift


    【解决方案1】:

    编辑: 向客户端发送太多数据被认为是不好的事情,假设您将有 70,000 个该 sql 的结果,您真的会向用户发送 15MB 的数据吗?我不这么认为:)。你应该学习如何使用 skiplimit

    来使用分页

    答案:

    好吧,首先让我们改进你的 PHP 代码

    if ($result = $mysqli->query("SELECT id, fullname, mobile, mobilepref, address, autofill FROM users WHERE email = '$email';")) {
    
        $userData = [];
        while ($row = $result->fetch_assoc()){
            $userData[] = $row;
        }
    
        //no need to write a json by your self, php does it alone
        echo json_encode($userData);
    
        //add all mysqli->close()
    
    }
    

    快速:

    //you did this:
    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary
    

    然后迭代它

    for (k,v) in jsonData {
       println("jsonData[\(k)] = \(v)") //a row from your SQL result
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多