My problem is that the Swift 3 iOS code doesn't update the mysql database, it's supposed to whenever the sendData() code is initialized to add +1 and update the testPop column database.
My app has a tableview with rows of different objects, I have a button in each row which gets the indexPath.row to know which button in which row it was clicked in. Using that information, my sendData() code is supposed to add +1 to testPop of the specific row.
Hope that made sense, thank you.
Swift 3 Code: Sending Data to database:
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 Code:
<?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 code:
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');
http://exampleip.org/tests.phpwhich the responsibility is to update your MySQL tables.