我在PHP语句中使用了Swift POST方法和PHP以及mysql查询,但是我想使用GET方法做同样的事情。
我的代码在90%的时间内执行完美,但由于某种原因,它偶尔会出错并且不会检索任何JSON对象。我想尝试使用GET来查看错误是否会停止发生。
以下是我的Swift代码:
let loadSongsID = self.partyID[0]
let bodyData = "partyID=\(loadSongsID)" //To get them in php: $_POST['name']
let songURL: NSURL = NSURL(string: "http://myserverURL/loadSongsIntoParty.php")!
var postData:NSData = bodyData.dataUsingEncoding(NSUTF8StringEncoding)!
var songsRequest: NSMutableURLRequest = NSMutableURLRequest(URL:songURL)
songsRequest.HTTPMethod = "POST"
songsRequest.HTTPBody = postData
var responseError: NSError?
var response: NSURLResponse?
var urlData: NSData! = NSURLConnection.sendSynchronousRequest(songsRequest, returningResponse: &response, error: &responseError)
var allSongs: AnyObject! = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions(0), error: &responseError)
if let songsJson = allSongs as? Array<AnyObject> {
println(songsJson)
for index in 0...songsJson.count-1 {
let indivSong : AnyObject? = songsJson[index]
let collection = indivSong! as Dictionary<String, AnyObject>
let track : AnyObject! = collection["track"]
let artist : AnyObject! = collection["artist"]
let trackURI : AnyObject! = collection["trackURI"]
let vote: AnyObject! = collection["vcount"]
self.tracks.append(track as String)
self.names.append(artist as String)
self.tracksURI.append(trackURI as String)
self.votes.append(vote as String)
}
}
我的PHP:
<?php
// Create connection
$con = mysqli_connect("######", "######", "######", "#######");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Change character set to utf8
mysqli_set_charset($con, "utf8");
$ID = $_POST['partyID'];
$sql = "select track, artist, trackURI, vcount from votes where PID = '$ID'";
// Check to see if there are results
if ($result = mysqli_query($con, $sql)) {
// If so, then create a results array and a temporary one to hold date
$resultArray = array();
$tempArray = array();
// loop through each row in the result set
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);
?>