我有一个应用程序的 VC,它获取所有需要的变量,应该通过 POST 请求将它们传递到一个 php 文件,在那里它们被存储并发送到数据库。当变量没有在数据库中设置时,问题就来了(我相信连接做得很好)。 php 文件与执行相同操作的 Android 应用程序一起工作正常(因此使用 Android 应用程序可以很好地存储变量)。
如果你能给我一些帮助,我将不胜感激。
swift
@IBAction func modPres(_ sender: AnyObject) {
let postDataURL = "https://www.juankarfollador.com/login_app.php"
let url: NSURL = NSURL(string: postDataURL)!
let request: NSMutableURLRequest = NSMutableURLRequest(url:url as URL)
request.httpMethod = "POST"
request.httpBody = user.data(using: String.Encoding.utf8)
request.httpBody = l_origen.data(using: String.Encoding.utf8)
request.httpBody = l_destino.data(using: String.Encoding.utf8)
request.httpBody = num_pal.data(using: String.Encoding.utf8)
request.httpBody = String(precio).data(using: String.Encoding.utf8)
request.httpBody = texto.data(using: String.Encoding.utf8)
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
{
(response, data, error) in
print(response!)
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
if statusCode==200 {
print("Connection Successful")
} else {
print("Connection Failed (!200)")
}
}
}
}
PHP
$precio = $_POST['precio'];
$texto = $_POST['texto'];
$user = $_POST['user'];
$l_origen = $_POST['l_origen'];
$l_destino = $_POST['l_destino'];
$num_pal = $_POST['num_pal'];
$modificar = $_POST['modificar'];
define('HOST','***');
define('USER','***');
define('PASS','***');
define('DB','***');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
mysqli_set_charset( $con, 'utf8');
//Cliente
$sql = "UPDATE users SET precio='$precio', text_cli='$texto', l_origen='$l_origen', l_destino='$l_destino', num_pal='$num_pal' WHERE username='$user' AND text_cli=''";
mysqli_query($con,$sql);
控制台打印“Connection Successful”,这就是我认为连接成功的原因(不过我不确定,因为我是 Swift 的新手)
最佳答案
您正在一遍又一遍地覆盖请求的 httpBody
。
最重要的是,您没有传递与您的帖子变量的值
相匹配的键
。
你需要一些类似的东西:
let paramString = "precio=\(precio)&texto=\(texto)&user=\(user)&l_origen=\(l_origen)&l_destino=\(l_destino)&num_pal=\(l_destino)&modificar=\(modificar)"
request.httpMethod = "POST"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
在您的 PHP
中,我没有看到验证,如果您没有验证,那么您真的应该添加它,因为它与您的数据库交互。
更不用说您暴露于 SQL
注入(inject)。
关于php - 快速发布任何内容的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41384446/