I had tried many times in Swift, seem the problem happened in the PHP file. i dont know the data tpye of $revaID correct i get $revaID value from swift, i want to use revaID to delete row from table reservation ,it is auto created.please help
<?php
$host = "127.0.0.1";
$username = "root";
$password = "password";
$dbname = "project";
// Connect to server
$connect=mysqli_connect("127.0.0.1", "root", "password","project")
or die ("Sorry, unable to connect database server");
$revaID = $_POST["revaID"]; ;
$UserID = $_["UserID"];
// Run the query
$query = "DELETE FROM reservation WHERE revaID = '$revaID'";
$result = mysqli_query($connect,$query);
////////////////////ignore///////// //////////////////
if ($result) {
print $result;
print "Suss";
print $revaID;
} else {
print "Failed to delete record!";
print(mysqli_error($connect));}
////////////////// ////////////////// //////////////////
////////////////////ignore////////////////////////
if ($revaID){
set_include_path('/Library/WebServer/Documents/');
$id2 = array();
$id2['revaID'] = $revaID;
// Loop through each row in the result set
$json = json_encode($id2, JSON_NUMERIC_CHECK );
file_put_contents('deleterevaID.php',$json,FILE_USE_INCLUDE_PATH);}
////////////////// //////////////////
mysqli_close($connect);
?>
and this is my swife code, when editingStyle == .delete , i got $revaID.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
let UserID = userinfo[indexPath.row]
// print(UserID)
userinfo.remove(at:indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
// Service.shared.deletePost(revaID:UserID.revaID) { (err) in
// }
let urlStr = "http://localhost/deleteres.php"
if let url = URL(string: urlStr) {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "DELETE"
let body = "revaID=\(UserID.revaID)"
print("ID:",UserID.revaID)
if let data = body.data(using: .utf8) {
let dataTask = URLSession.shared.uploadTask(with: urlRequest,
from: data, completionHandler: {
data, response, error in
if let error = error{
print("error: \(error.localizedDescription)")
}
// print(UserID.revaID)
//self.refreshBtnClicked(self)
})
dataTask.resume()
}
}
}
}
in a swift file, you are sending data with get method and in a PHP file you are trying to get data with post method.
so instead of this :
$revaID = $_POST["revaID"]; ;
try to get data by get method
$revaID = $_GET["revaID"]; ;
Related
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'];
I want to get the name of the current logged in user and send it to php ..
I tried to type a name and it worked perfectly.
But if I want to send a variable like in here It doesn't work:
//let defaultValues = UserDefaults.standard
//let username1 = defaultValues.string(forKey: "username");
//let username2 = NSFullUserName()
let username2 = NSUserName()
let urlPath: String =
"http://127.0.0.1/PhpstormProjects/myiosapp/v1/MyWishes.php?username=username2" // here is the problem
func downloadItems() {
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
...
I think it's because it sends the variable as a string.
This is the line of code in php (works good when sending a string):
$username = $_GET['username'];
$sql = "SELECT * FROM ITEM WHERE username = $username";
Any suggestions?
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;
}
}
}
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,
What could be wrong with this code, I'm trying to get into my MAMP sever which is turned on, I have one php file in the server where I'm testing the connections and such, this:
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
echo $username
echo $password
if($username && $password) {
$db_name = 'DBTest';
$db_user = 'pedro';
$db_password = 'pedro';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
And in Xcode The app currently has 3 views all in swift, but the important one is this:
//
// LogInViewController.swift
// ParkingApp
//
// Created by Pedro Alonso on 02/06/15.
// Copyright (c) 2015 Pedro Alonso. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController {
#IBOutlet weak var loginLabel: UILabel!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
#IBAction func enterTapped(sender: UIButton) {
var username: String = usernameField.text
var password: String = passwordField.text
if ( username.isEmpty || password.isEmpty) {
var alertView: UIAlertView = UIAlertView()
alertView.title = "Failed"
alertView.message = "Error in the username or password"
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
} else {
var post: String = "username=\(username)&password=\(password)"
NSLog("Post data: %#", post)
println(post)
var url: NSURL = NSURL(string: "http://localhost:8888/jsonlogin2.php")!
var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)!
var postLenght: String = String(postData.length)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLenght, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var responseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
if urlData != nil {
let res = response as! NSHTTPURLResponse!
println(urlData)
NSLog("Response code: %ld", res.statusCode)
if (res.statusCode >= 200 && res.statusCode < 300) {
var responseData: NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)!
NSLog("Response: ==> %#", responseData)
var error: NSError?
let jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
let succes: Int = jsonData.valueForKey("succes") as! Int
if succes == 1 {
NSLog("Login Success")
var prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var errorMsg: String?
if jsonData["error_message"] as? String != nil {
errorMsg = jsonData["error_message"] as! String?
} else {
errorMsg = "Unknown error"
}
var alertView: UIAlertView = UIAlertView()
alertView.title = "Sign in failed"
alertView.message = errorMsg
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = responseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
}
The .php file is in /Applications/MAMP/htdocs, what is not clear is why is giving me response code 500, and I'm at a lost not sure why is happening. Any help?? Thanks.
EDIT: The response:
<NSHTTPURLResponse: 0x7fc42149ac60> { URL: http://localhost:8888/jsonlogin2.php } { status code: 500, headers {
Connection = close;
"Content-Length" = 0;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 04 Jun 2015 12:11:35 GMT";
Server = "Apache/2.2.29 (Unix) mod_wsgi/3.4 Python/2.7.8 PHP/5.6.7 mod_ssl/2.2.29 OpenSSL/0.9.8zd DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.8 Perl/v5.20.0";
"X-Powered-By" = "PHP/5.6.7";
} }
I can access from safari in the simulator to localhost:8888, so there is no connection problem.
EDIT2: So it is the request apparently, because it tells me invalid data skipping all and returning this:
2015-06-04 17:16:11.914 ParkingApp[3777:126598] Response: ==> {"success":0,"error_message":"Invalid Data."}
What could be wrong with the way I've done the request?
EDIT2: I have changed the code and activated the mysql log to see the queries, but still the $stmt->get_result() or fetch() are doing nothing and I do not know why. I'm not doing it throughout IOS but simple browser here is the troublesome part.
Modified part:
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$query = "SELECT dataOne,password FROM users WHERE username = ? and password = ?";
if ($stmt = $mysqli->prepare($query)) {
//$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
//$stmt->debugDumpParams();
echo $stmt->sqlstate;
var_dump($stmt);
/* bind result variables */
//$stmt->bind_result($dataOne,$password);
$result = $stmt->get_result();
printf("test: ", $dataOne, $password);
//fetch value
while($stmt->fetch()) {
echo $dataOne;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($result != null) {
error_log("User $username: password match.");
echo '{"success":1, "dataOne:"'.$dataOne.'}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
The $stmt is not retuning anything on the get_result() or is not going into the while(fetch()) I'm just do not know now. Any help?
Well, if your web server is throwing http error code 500 (Internal Error) it is because your PHP script is crashing. I would try and read the php log, and try and do some debugging of the php script.
Maybe there is something wrong with the posted data from your iOS app, making the php script fail?
Also accessing localhost:8888 from safari in this case would not prove that the php script is working, as it requires you to post any data for the script to execute. if($_POST) {. By just browsing that script, the if statement will never be true.
EDIT:
It some times helps to verify one component at a time. Try building a simple html form that posts username and password against your server (http://localhost:8888/jsonlogin2.php). When you see this working as expected, move on to making sure the app works. This way you can tell if your errors are on the server (php script) or in your app.
It's also good to check $_POST like this:
if (!empty($_POST)) {}
This will check if the $_POSTis empty.
Your app is also using application/x-form-urlencoded and my guess is that this should be: application/x-www-form-urlencoded.
But once again. Make a local html form, and make certain that your php script is working, and then move over to the app.