Swift代码不更新MySQL数据库

时间:2016-12-04 07:54:07

标签: php ios mysql json swift

我的问题是Swift 3 iOS代码没有更新mysql数据库,它应该在sendData()代码初始化时添加+1并更新testPop列数据库。

我的应用程序有一个包含不同对象行的tableview,每行都有一个按钮,它获取indexPath.row以了解它被单击的行中的哪个按钮。使用该信息,我的sendData()代码应该是将+1添加到特定行的testPop。

希望有意义,谢谢。

Swift 3代码:将数据发送到数据库:

func sendData() {

    let postDataURL = "http://exampleip.com/Send.php"
    let url: NSURL = NSURL(string: postDataURL)!
    let request: NSMutableURLRequest = NSMutableURLRequest(url:url as URL)

    let bodyData = String(1)

    request.httpMethod = "POST"
    request.httpBody = bodyData.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代码:

<?php

$host = "host";
$db = "db";
$user = "user";
$pass = "pass";

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

// Guessing: Posting into MySQL Object
$id = $_POST["id"];

// Checking if connection can be established
if(!$connection){
    die("Connection Failed");
}
else
{
    // Selecting Database
    $dbconnect = mysql_select_db($db, $connection);

    // Check if it can connect to Database
    if(!$dbconnect){
        die("Unable to connect to Database");
    }
    else
    {
        $query = sprintf("UPDATE tests SET testPop=testPop+1 WHERE id = %d", $id);

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

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

?>

MySQL代码:

CREATE TABLE IF NOT EXISTS `tests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`testName` varchar(255) DEFAULT NULL,
`testPop` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

INSERT INTO `tests` (`id`, `testName`, `testPop`) VALUES
(1, 'Test 1', '0'),
(2, 'Test 2', '0'),
(3, 'Test 3', '0'),
(4, 'Test 4', '0'),
(5, 'Test 5', '0'),
(6, 'Test 6', '0'),
(7, 'Test 7', '0'),
(8, 'Test 8', '0'),
(9, 'Test 9', '0'),
(10, 'Test 10', '0'),
(11, 'Test 11', '0'),
(12, 'Test 12', '0');

1 个答案:

答案 0 :(得分:0)

因为您在PHP代码中阅读了id,所以您需要帖子正文包含id

let bodyData = String(1)

应该是这样的:

let itemId = String(1)
let bodyData = "id=\(itemId)"