-1

What should I add to my Swift code to pass a variable into the following PHP script? My PHP script is waiting for a value customerName in $ID = $_POST['customerName'];

How can I hard-code a value in my Swift code to send the value?

Swift Code:

import Foundation

protocol FeedDetailProtocol: class {
    func itemsDownloaded(items: NSArray)
}


class FeedDetail: NSObject, URLSessionDataDelegate {



    weak var delegate: FeedDetailProtocol!



func downloadItems() {


    let url = URL(string: "https://www.example.com/test/test1.php")!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"**strong text**
    let parameters: [String: Any] = ["customerName": "John"]

    request.httpBody = parameters.percentEscaped().data(using: .utf8)

    let task = defaultSession.dataTask(with: url) { (data, response, error) in

        if error != nil {
            print("Error")
        }else {
            print("details downloaded")
            self.parseJSON(data!)
        }

    }

    task.resume()
}

    func parseJSON(_ data:Data) {

        var jsonResult = NSArray()

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

        } catch let error as NSError {
            print(error)

        }

        var jsonElement = NSDictionary()
        let stocks = NSMutableArray()

        for i in 0 ..< jsonResult.count
        {

            jsonElement = jsonResult[i] as! NSDictionary

            let stock = DetailModel()

            //the following insures none of the JsonElement values are nil through optional binding
            if let rma = jsonElement["rma"] as? String,
                let customer = jsonElement["customer"] as? String,
                let manufacturer = jsonElement["manufacturer"] as? String,
                let model = jsonElement["model"] as? String

            {

                stock.rma = rma
                stock.manufacturer = manufacturer
                stock.model = model
                stock.customer = customer

            }

            stocks.add(stock)

        }

        DispatchQueue.main.async(execute: { () -> Void in

            self.delegate.itemsDownloaded(items: stocks)

        })
    }
}

PHP Script:

$con=mysqli_connect("localhost","username","password","dbName");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$ID = $_POST['customerName'];

$sql = "SELECT customer, rma, manufacturer, model, status FROM Equipment 
        WHERE customer = '$ID' ";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    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 json_encode($resultArray);
}

mysqli_close($con);
  • Are you receiving an error, or just not getting the value? I say this because the code you posted has a syntax error which would cause a 500 error in PHP (`$sql = "SELECT customer, rma, manufacturer, model, status FROM Equipment WHERE customer = '$ID';` should be `$sql = "SELECT customer, rma, manufacturer, model, status FROM Equipment WHERE customer = '$ID'";` - you're missing the trailing double-quote on the end of the string). – Chris White May 02 '19 at 13:21
  • @ChrisWhite The value is not passing from the Swift app to the php script –  May 02 '19 at 13:23
  • @ChrisWhite The missing trailing double quote is my fault, I forgot to add it to my post when copying. But the issue is still not solved –  May 02 '19 at 13:28
  • Can you please take a look, the issue is definitely the Swift part –  May 02 '19 at 13:29
  • Sorry, I don't know Swift at all. – Chris White May 02 '19 at 13:31

1 Answers1

0

Your PHP code take POST value ($ID = $_POST['customerName']) so you need to create POST request.

Something like this:

let url = URL(string: "https://www.example.com/test1/test1.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = ["customerName": "John"]`

HTTP Request in Swift with POST method