从Swift将数据发布到PHP方法(选择查询)

时间:2019-05-01 21:47:44

标签: php mysql swift

我目前拥有以下带有选择查询的PHP脚本,其中包含所有硬编码值。如何获取我的Swift应用提供的价值?

有没有一种方法可以轻松地编辑以下代码,我还必须具有一个POST值,而不是在PHP脚本中具有一个硬编码的值?

    // Create connection
$con=mysqli_connect("localhost”,”username”,”password”,”dbName”);

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$sql = "SELECT name FROM TABLE 
        WHERE name = ‘$CHANGE THIS’ ";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);

我当前在Swift中的代码如下:

然后将我从SQL查询中获取的数据放入数组中,并在UITable中设置格式:

import Foundation

protocol FeedDetailProtocol: class {
    func itemsDownloaded(items: NSArray)
}


class FeedDetail: NSObject, URLSessionDataDelegate {



    weak var delegate: FeedDetailProtocol!

    let urlPath = "https://www.example.com/test/test1.php"

    func downloadItems() {

        let url: URL = URL(string: urlPath)!
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)

        let task = defaultSession.dataTask(with: url) { (data, response, error) in

            if error != nil {
                print("Error")
            }else {
                print("details downloaded")
                self.parseJSON(data!)
            }

        }

        task.resume()
    }

    func parseJSON(_ data:Data) {

        var jsonResult = NSArray()

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

        } catch let error as NSError {
            print(error)

        }

        var jsonElement = NSDictionary()
        let stocks = NSMutableArray()

        for i in 0 ..< jsonResult.count
        {

            jsonElement = jsonResult[i] as! NSDictionary

            let stock = DetailModel()

            //the following insures none of the JsonElement values are nil through optional binding
            if let name = jsonElement["name"] as? String,


            {
                print(name)
                stock.name = name


            }

            stocks.add(stock)

        }

        DispatchQueue.main.async(execute: { () -> Void in

            self.delegate.itemsDownloaded(items: stocks)

        })
    }
    }

0 个答案:

没有答案