I have got a VC of an app that gets all the variables needed and should pass them through a POST request to a php file, where they are stored and sent to a database. The problem comes when the variables are not set in the database (I believe the connection is well done). The php file is working fine with an Android app that does the same (so the variables are well stored using the Android app).
I would be grateful if you could give me some help.
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);
The console prints "Connection Successful", and this is why I think the connection is well done (I am not sure though, as I am pretty new to Swift)
You are overriding the httpBody of your request over and over.
On top of that you are not passing the keys matching the values of your post variables.
You need something along these lines:
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)
In your PHP I don't see a validation, if you don't have it then you should really add it because it interacts with your db.
Not to mention that you are exposed to SQL injections.
Related
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
I'm trying to get parameters in my php file when I'm posting from SWIFT (login file)
This is my php file :
<?
$json = array();
$json['username'] = $_POST['username'];
$json['password'] = $_POST['password'];
$json['result'] = "false";
$json['id_familia'] = 148;
$json['id_centre'] = 2;
$json['web'] = "www.cec-escolalolivar.cat";
echo json_encode($json);
?>
This is swift code (of course I've tried with different options, sync, not sync, ....)
let url : NSURL = NSURL(string: "http://www.cec-info.cat/app/config.inc.main_families_json.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
let bodyData="data=xgubianas#gmail.com"
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 as Any)
if let data = data{
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print (json)
}
catch
{
print (error)
}
}
}
I am trying to make registration in swift3 with mysql
but there is some thing wrong ,
when I run my app and make register return msg "some fields are empty"
In php code:
$fullname = htmlentities($_REQUEST["fullname"]);
$username = htmlentities($_REQUEST["username"]);
$email = htmlentities($_REQUEST["email"]);
$password = htmlentities($_REQUEST["password"]);
$phone = htmlentities($_REQUEST["phone"])
swift code:
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "http://localhost/php/register.php?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "fullname=\(FirstName.text)%20\(LastName.text)&username=\(UserName.text)&email=\(Email.text)&password=\(Password.text)&phone=\(Phone.text)"
request.httpBody = body.data(using: String.Encoding.utf8)
let task = session.dataTask(with: url!) {data, response, error in
if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
print(json)
}
} catch {
print("error in JSONSerialization")
}
}
}
task.resume()
I think you missed this
let task = session.dataTask(with: request) {data, response, error in
replace url with request
Good morning,
I'm trying to send a variable (id_post) through a PHP file using Swift and the .php file it's called, but ¨id_post¨ is empty, because when I print the value of ¨id_post¨ it's always empty.
Do you know why is this happening? I have used the same function in another project from 1 month ago and there is working and here isn't. Am I missing something?
Also I have tested the ¨postString¨ value and it's always correct (id_post=64).
Here is my Swift code:
func requestPost () {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.website.com/post.php")!)
request.HTTPMethod = "POST"
let postString = "id_post="+id_post
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
print("post: \(responseString)")
self.posts = self.parseJsonData(data!)
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
task.resume()
}
Here is my PHP code:
$dbhost="localhost";
$dbusuario="dbuser";
$dbpassword="dbpassword";
$db="db";
$conexion = mysql_connect($dbhost, $dbusuario, $dbpassword);
mysql_select_db($db, $conexion);
mysql_query("SET NAMES 'utf8'");
$id_post=$_POST['id_post'];
$return_arr = array();
$fetch = mysql_query("SELECT * FROM posts WHERE id=$id_post");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC))
{
$row_array['id'] = $row['id'];
$row_array['image'] = $row['image'];
array_push($return_arr,$row_array);
}
echo '{"post": '.json_encode($return_arr).'}';
Thanks in advance,
Regards.
The only thing I had to change it was the "http://www.website.com" to "http://website.com". I don't know why it wasn't working that way, but I post the solution if someone has the same weird problem.
Regards,
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"];
:|