向PHP web服务器发送到MySQL的Swift JSON请求
我是一个初学者,正在做一个学习项目。我想通过php文档将swift变量传输到我的web服务器。这意味着对PHP的快速请求 这是我的Swift代码:向PHP web服务器发送到MySQL的Swift JSON请求,php,mysql,json,swift,request,Php,Mysql,Json,Swift,Request,我是一个初学者,正在做一个学习项目。我想通过php文档将swift变量传输到我的web服务器。这意味着对PHP的快速请求 这是我的Swift代码: let myUrl = URL(string: "http://example.net/stock_service3.php"); var request = URLRequest(url:myUrl!) request.httpMethod = "POST"// Compose a query string
let myUrl = URL(string: "http://example.net/stock_service3.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "firstName=51&lastName=6";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
// You can print out response object
print("response = \(String(describing: response))")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(String(describing: firstNameValue))")
}
} catch {
print(error)
}
}
task.resume()
这是PHP和MySQL代码:
<?php
// Create connection
$con=mysqli_connect(".......".........".........");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];
// Select all of our stocks from table 'stock_tracker'
$sql ="SELECT m.*
, ( ACOS( COS( RADIANS( $firstName) )
* COS( RADIANS( m.latitude ) )
* COS( RADIANS( m.longitude ) - RADIANS( $lastName) )
+ SIN( RADIANS($firstName ) )
* SIN( RADIANS( m.Latitude) )
)
* 6371
) AS distance_in_km
FROM TankBilliger m
HAVING distance_in_km <= 100
ORDER BY distance_in_km ASC
LIMIT 100";
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
不知何故,它不起作用,我也不知道为什么。“不知何故,它不起作用,我也不知道为什么”什么是“它”?哪一行?您需要更改它,这样,如果它无法连接或运行查询,它仍然会返回有效的JSON。目前,您只是重复一个错误,因此无法将其解析为JSON。请阅读-总结是,这不是解决志愿者问题的理想方式,可能会对获得答案产生反作用。请不要将此添加到您的问题中。