使用带参数的URL从Swift中的远程数据库更新记录

时间:2015-03-30 18:47:06

标签: php database swift

我想在url中传递一个整数参数来更新远程数据库中记录的字段,但是我收到了错误。怎么办?我的php工作但不是从Swift调用。如何在Swift中执行用于更新数据库记录的php文件?

以下是服务器上用于更新记录的php。如何从Swift应用程序运行它?从网上我这样做它运行(IdTask是唯一的):

http://.../updateonetasktocompleted.php?x=2

<?php
$host = "localhost"; //database host server
$db = "dbname"; //database name
$user = "dbuser"; //database user
$pass = "passwd"; //password

$connection = mysql_connect($host, $user, $pass);

//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");  
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db("dbname", $connection);

//Check to see if we could select the database
if(!$dbconnect)
{
    die("Unable to connect to the specified database!");
}
else
{
    $idtask_selected = $_GET['x'];

    $query = "UPDATE ProtocolSets_Protocols SET `ProtocolSets_Protocols`.`Completed`='Yes' WHERE `ProtocolSets_Protocols`.`IdTask`= $idtask_selected";        

    $resultset = mysql_query($query, $connection);

    echo "Successfully added ";
    echo $query;
}
}
?>

2 个答案:

答案 0 :(得分:0)

如果您尝试从Swift代码运行命令行php脚本,则可以使用NSTask:

var task = NSTask()
task.launchPath = "/path/to/your/script/script.php"
task.arguments = ["25"]
task.launch()

但我可能会误解你的问题,因为你没有提供很多背景信息。

答案 1 :(得分:0)

我想出了一种方法:

let currentIdTask:Int? = NSUserDefaults.standardUserDefaults().stringForKey("selectedIdTask")?.toInt()

var url: NSString = "http://.../updateonetasktocompleted.php?x=\(currentIdTask!)"
url = url.stringByReplacingOccurrencesOfString(" ", withString: "%20")
url = url.stringByReplacingOccurrencesOfString("/n", withString: "%0A")
println(url)

var data = NSData(contentsOfURL: NSURL(string: url)!)
var result = NSString(data: data!, encoding: NSUTF8StringEncoding)
println(result)