Swift httppost data not inserting to MySQL database - php

I am trying to send data to php and insert it to mysql database but it doesn't seem to work. I have tried sending data to php just to encode it to json and echo it back to swift and it returns a result so it means that the php file received the data. However inserting the data is not working.
swift2 httppost
func post() {
let myUrl = NSURL(string: "http://localhost:8080/json/json.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST"
// Compose a query string
let postString = "firstName=James&lastName=Bond";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let’s convert response sent from a server side script to a NSDictionary object:
do{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
}
}catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
}
task.resume()
}
json.php
<?php
// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array
$conn = mysqli("localhost", "root", "root", "notify");
$query = mysqli_query($conn, "INSERT INTO user values('', '$firstName',
'$lastName')");
?>

If having the server just echo the request works, then the problem rests within the server, not the client code. I would suggest adding some error handling in the PHP code:
<?php
// specify that this will return JSON
header('Content-type: application/json');
// open database
$con = mysqli_connect("localhost","user","password","notify");
// Check connection
if (mysqli_connect_errno()) {
echo json_encode(array("success" => false, "message" => mysqli_connect_error(), "sqlerrno" => mysqli_connect_errno()));
exit;
}
// get the parameters
$field1 = mysqli_real_escape_string($con, $_REQUEST["firstName"]);
$field2 = mysqli_real_escape_string($con, $_REQUEST["lastName"]);
// perform the insert
$sql = "INSERT INTO user (first_name, last_name) VALUES ('{$field1}', '{$field2}')";
if (!mysqli_query($con, $sql)) {
$response = array("success" => false, "message" => mysqli_error($con), "sqlerrno" => mysqli_errno($con), "sqlstate" => mysqli_sqlstate($con));
} else {
$response = array("success" => true);
}
echo json_encode($response);
mysqli_close($con);
?>
Notes:
I wouldn't recommend logging in as root.
Make sure you use mysqli_real_escape_string to protect yourself against SQL injection attacks (see point 1).
I don't know if your user table has other fields in it, but if so, you might want to specify the column names in the insert statement. Even if you only have those two columns, it's a good way to "future-proof" your code.
Note, I've changed this to generate JSON response. I do that because it makes it easier for the client code to parse and handle the response. I'll leave the NSJSONSerialization to you.

Related

Creating task for POST request to PHP script to add entries in MySQL database

I would like to implement an IOS app via swift 5 to adjust a MySQL database triggered by a PHP script. I try to use the post request to handover the following parameters:
teamName = "Testteam"
teamCount = "member"
After some testing I found out, that parameters are not handover to PHP script (they are empty) and I don't know why.
Swift Code
let URL_SAVE_TEAM ="http://www.mydomain.de/createteam.php"
#IBOutlet weak var textFieldName: UITextField!
#IBOutlet weak var textFieldMember: UITextField!
#IBAction func Login(_ sender: UIButton) {
//created NSURL
let requestURL = NSURL(string: URL_SAVE_TEAM)!
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: requestURL as URL)
//setting the method to post
request.httpMethod = "POST"
//getting values from text fields
let teamName = textFieldName.text
let memberCount = textFieldMember.text
//creating the post parameter by concatenating the keys and values from text field
//let postParameters = "name="+teamName!+"&member="+memberCount!;
//adding the parameters to request body
request.httpBody = postParameters.data(using: String.Encoding.utf8)
//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) in
if error != nil {
print("error is \(String(describing: error))")
return
}
do { //parsing the response
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary //converting resonse to NSDictionary
print(myJSON)
//parsing the json
if let parseJSON = myJSON {
//creating a string
var msg : String!
//getting the json response
msg = parseJSON["message"] as! String?
//printing the response
print(msg!)
}
} catch {
print(error)
}
}
//executing the task
task.resume()
}
PHP script on server
<?php
//creating response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_GET['name'];
$memberCount = $_GET['member'];
$fp = fopen ('debug.log' , "w"); // Datei öffnen
fwrite ($fp , 'test'); // Dateiinhalt in die Datei schreiben
fwrite ($fp , $teamName); // Dateiinhalt in die Datei schreiben
fwrite ($fp , $memberCount); // Dateiinhalt in die Datei schreiben
fclose ($fp); // Datei schließen
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
?>
The PHP script is sending the error message (Could not add team) because the variable $teamName and $memberCount are empty. The overall connection to the PHP script seems to work.
You are using POST method, so you should get POST values not GET values:
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];

PHP script isn't inserting Swift Data into MYSQL database

In the IOS app I'm trying to make I am trying to get user input and submit it to a MYSQL database, however the database isn't updating. Here is the swift function that is called to submit the data:
func submit_data(){
let request = NSMutableURLRequest(url: NSURL(string: "omitted")! as URL)
request.httpMethod = "POST"
let postString = "a=\(bar_name)&b=\(user_data)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
print(postString)
}
task.resume()
}
Here is my PHP code:
<?PHP
//Create connection
$con=mysqli_connect("localhost","username","password","covermeo_coverme_data");
//check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO User_Data (Bar, Cover)
VALUES ('".$_POST["a"]."','".$_POST["b"]."')";
$result = mysqli_query($conn,$sql);
// Close connections
mysqli_close($con);
?>
Here is a screenshot of the MYSQL database.
Solution:
open Info.plist
add a key App Transport Security Settings
add a sub key Allow Arbitrary Loads Boolean value - YES

Data does not being sent to Database because it cannot be read

I'm working on a project where I need to send some data to the remote database. So I'm developing an iOS app using Swift 3.1 and when I try to send data to the database it says,
The data couldn’t be read because it isn’t in the correct format.
Also there is another error;
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
This is my swift code:
let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure
{
let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()
let postParameters = "{\"usermobilenum\":\(String(describing: userMobileNumber!)),\"contactnum\":\(contact.phoneNumber!)}";
request.httpBody = postParameters.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
data, response, error in
if error != nil
{
print("error is \(String(describing: error))")
return;
}
do
{
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = myJSON
{
var msg : String!
msg = parseJSON["message"] as! String?
print(msg)
}
}
catch
{
print(error.localizedDescription)
print(error)
}
}
print("Done")
task.resume()
}
This is my PHP in remote database:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
require 'connectDB.php';
$userPhone = $_POST["usermobilenum"];
$contactNum = $_POST["contactnum"];
$query = "SELECT * FROM user WHERE UserMobNum='".$userPhone."'"; // Usermobile is registered.SIP exists.
if($results= mysqli_query($connect,$query))
{
if(mysqli_num_rows($results)>0)
{
$i=0;
while($rows=mysqli_fetch_assoc($results))
{
$sip[$i] = $rows["SIP"];
$i++;
}
$queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
if(mysqli_query($connect,$queryToAddData))
{
//Return success message to the app
echo "Success"
}
else
{
die(mysqli_error($connect));
}
}
else
{
$availableSIP=false;
while($availableSIP==false) // Assign a random value until it's being a valid one.
{
$sip[0]=rand(1,9999);
$queryToCheck = "SELECT * FROM user WHERE SIP='".$sip[0]."'";
if($results= mysqli_query($connect,$queryToCheck))
{
if(mysqli_num_rows($results)==0)
{
$availableSIP=true;
}
}
}
$queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
if(mysqli_query($connect,$queryToAddData))
{
//Return success message to the app
echo "Success"
}
else
{
die(mysqli_error($connect));
}
}
}
else
{
echo "First Level Failure!";
die(mysqli_error($connect));
}
mysqli_close($connect);
}
else
{
echo "Failed in POST Method"
}
?>
What I did
Went through all of stack overflow and other site suggestions but had no luck. I even checked my jSon string using a json validator and it passed. This is how my jSon string looks like.
{"usermobilenum":1234567890,"contactnum":9345}
However after some search I found that this happens because Remote database PHP sends this error message. So I checked each and every variable in PHP but couldn't find any problem. Also this couldn't be a problem with PHP cause I work with those exact php files when I connect to via my android app. That works fine. But in iOS it generates that error. Can someone help me please?
UPDATE
This is insertdataTest.php file:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$userPhone = $_POST["usermobilenum"];
echo $userPhone;
mysqli_close($connect);
}
else
{
echo json_encode("Failed in POST Method");
}
?>
{"usermobilenum":1234567890,"contactnum": 9345} - this is treated as a String. It's not a VALID JSON.
Updated code:
let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure {
let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()
let postParameters = NSMutableDictionary()
postParameters["usermobilenum"] = userMobileNumber
postParameters["contactnum"] = contact.phoneNumber!
let jsonData = try? JSONSerialization.data(withJSONObject: postParameters, options: .prettyPrinted)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error is \(String(describing: error))")
return;
}
do {
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
if let parseJSON: NSMutableDictionary = NSMutableDictionary(dictionary: myJSON as! NSMutableDictionary){
let msg = parseJSON["message"] as! String
print(msg)
}
}
catch {
print(error.localizedDescription)
print(error)
}
}
print("Done")
task.resume()
}
Buddy I debug you code and found that there is error in server response not in you code. try this and reply me ASAP please
before this line "let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary"
add "let str = String.init(data: data!, encoding: .utf8)
print(str ?? "error")"
I am waiting please.

Parsing JSON array to Server with Swift 3.0

I am trying to send a JSON array to the web server. I have looked at several examples online i.e. https://www.youtube.com/watch?v=aTj0ZLha1zE&t and Saving CoreData to a Web Server with Swift 3.0 that have demonstrated how to parse data but I am struggling to achieve this.
Below is my function which should send the data to the server:
func sendRecordToServer() -> [Record] {
let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Record")
fetchRequest.resultType = .dictionaryResultType
do {
let records = try context.fetch(fetchRequest)
if let jsonData = try? JSONSerialization.data(withJSONObject: records, options: []) {
// jsonData is a byte sequence, to view it you would need to convert to string
print(String(bytes: jsonData, encoding: String.Encoding.utf8))
let URL_SAVE_DATA = URL(string: "http://localhost/api/postdata.php")
let request = NSMutableURLRequest(url: URL_SAVE_DATA!)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(String(describing: error?.localizedDescription))")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
}
} catch {
print("Error fetching data from CoreData")
}
return records
}
After encoding the data to JSON, it prints out like this:
Optional([["record_id": 8EC9C1C9-7DD4-4343-B7CC-E4615FDDA150, "name": John ], ["record_id": 7EEA551D-9432-4737-99FB-6BFCF3A92D21, "name": Fred Smith]])
However as I try parsing it though to the server I get this and nothing get sent to the server:
responseString = Optional("")
Update:
Following up from the comment below here is what my posdata.php looks like:
<?php
//creating response array
$json = file_get_contents('php://input');
//echo $json shoulkd show the json string
$array = json_decode($json, true);
// var_dump($arr) should show the array structure
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$record_id = $_POST['record_id'];
$name = $_POST['name'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($record_id, $name)){
$response['error']=false;
$response['message']='Record added successfully';
}else{
$response['error']=true;
$response['message']='Could not add record';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
DBOperation:
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($record_id, $name)
{
$stmt = $this->conn->prepare("INSERT INTO record (record_id, name) values (?, ?)");
$stmt->bind_param("si", $record_id, $name);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}

PHP: how to get variables from a JSON(sent from a Swift iOS app) and respond with a JSON

I am developing an iOS app with Swift that should fetch some data from a MySQL database according to the user's location. I don't know PHP and I couldn't find a resource where it explains how to receive data from an app.
I have this PHP code:
<?php
// Create connection
$con=mysqli_connect("localhost","*******","*******","*******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM *******";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo "{ \"posts\": ";
echo json_encode($resultArray);
echo "}";
}
// Close connections
mysqli_close($con);
?>
as you can see when it is called it gets all the data from a table and returns it as a JSON. The next step that I want to do is to send my location from the Swift app with this code:
#IBAction func submitAction(sender: AnyObject) {
//declare parameter as a dictionary which contains string as key and value combination.
var parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String>
//create the url with NSURL
let url = NSURL(string: "http://myServerName.com/api") //change the url
//create the session object
var session = NSURLSession.sharedSession()
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST" //set http method as POST
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
}
courtesy from http://jamesonquave.com/blog/making-a-post-request-in-swift/
and I don't know how to "get"(accept, what function to use) this JSON:
{"items": [
{
"minLat": "43.000000",
"maxLat": "44.000000",
"minLon": "-79.000000",
"maxLon": "-78.000000",
}
]
}
from the app in order to have something like this in PHP:
$minLat = $json['minLat'];
$maxLat = $json['maxLat'];
$minLon = $json['minLon'];
$maxLon = $json['maxLon'];
$sql = "SELECT * FROM ******* WHERE latitude BETWEEN".$minLat." AND ".$maxLat." AND longitude BETWEEN ".$minLon." AND ".$maxLon;
Thank you
The answer is actually incredibly stupid-easy:
firstly nothing worked before I commented these two lines:
request.addValue("application/json", forHTTPHeaderField: "Content--Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Then I used a string instead of a JSON to send the POST data(it surely works with a JSON also, but this is what works at this moment):
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "minLat=43.0&maxLat=44.0&minLon=26.0&maxLon=27.0";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
and at the server side simply:
$minLat = $_REQUEST["minLat"];
$maxLat = $_REQUEST["maxLat"];
$minLon = $_REQUEST["minLat"];
$maxLon = $_REQUEST["maxLat"];
:|

Categories