Online Access to MySQL Databases

what should i do to fetch, publish and validate data from DB (MySQL) using swift? Can I only create php pages and link to them or is there a way to manage them? If so, how?

+3


source to share


1 answer


(Sorry for my English)

Yes you need a PHP script

In your swift file:

var bodyData = "name=value" //To get them in php: $_POST['name']


    let URL: NSURL = NSURL(string: "URL TO YOUR PHP FILE")
    let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
    {
            (response, data, error) in
            var output = NSString(data: data, encoding: NSUTF8StringEncoding) // new output variable
            var array = self.JSONParseArray(output)
    }

      



in php:

function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
    $status_header = 'HTTP/1.1 ' . $status;
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}

$name = $_POST['name']; // Like in the bodyData var

//Doing sql things

$result = array(
    "result" => "VARIABLE TO SEND BACK"
);


sendResponse(200, json_encode($result));

      

And if you don't want to get the result in an array, use this function:

func JSONParseArray(jsonString: String) -> Array<String> {
    var e: NSError?
    var data: NSData!=jsonString.dataUsingEncoding(NSUTF8StringEncoding)
    var jsonObj = NSJSONSerialization.JSONObjectWithData(
        data,
        options: NSJSONReadingOptions(0),
        error: &e) as Array<String>
    if e == 0 {
        return Array<String>()
    } else {
        return jsonObj
    }
}

      

+7


source







All Articles