Insert into remote database ASIFormDataRequest: Getting 400 Code, Bad Request

406 views Asked by At

I am trying to insert data into a database on a webserver. I am using MySQL, Appache and PHP

Xcode

*-(IBAction)saveRecord:(id)sender{
    UITextField *description_txtfield = (UITextField*)[self.tableView viewWithTag:11];
    description_string = description_txtfield.text;
    NSLog(description_string);

    NSURL *url = [NSURL URLWithString:@"http://192.168.1.140/~admin/qw/"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:description_string forKey:@"product_name"];
    [request setDelegate:self];
    [request startAsynchronous];

    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)requestFinished:(ASIHTTPRequest *)request {    

    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");        
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
    } else if (request.responseStatusCode == 200) {
        NSLog(@"OK");

    } else {
        NSLog(@"Unexpected error");
    }
     }*

- (void)requestFailed:(ASIHTTPRequest *)request
{    
    NSError *error = [request error];
    NSLog(error.localizedDescription);
}   

index.php has the following code inside to handle insert.

Function redeem() {

        // Check for required parameters
        if (isset($_POST["product_name"])) {

            // Put parameters into local variables
            $rw_app_id = $_POST["product_name"];
            // Add tracking of redemption
            $stmt = $this->db->prepare("INSERT INTO inventory (product_name) VALUES (?)");
            $stmt->bind_param($rw_app_id);
            $stmt->execute();
            $stmt->close();

        }
        sendResponse(400, 'Invalid request');
        return false;

    }

Can someone tell me what I am doing wrong here? I keep getting Invalid Code which is Bad Request-400.

1

There are 1 answers

0
Chris McKnight On

You were missing a header response and a return inside your if statement. Otherwise it falls through and get a 400 every time.

    Function redeem() {

            // Check for required parameters
            if (isset($_POST["product_name"])) {

                // Put parameters into local variables
                $rw_app_id = $_POST["product_name"];
                // Add tracking of redemption
                $stmt = $this->db->prepare("INSERT INTO inventory (product_name) VALUES (?)");
                $stmt->bind_param($rw_app_id);
                $stmt->execute();
                $stmt->close();
                sendResponse(200, 'Ok');
                return true;
            }
            sendResponse(400, 'Invalid request');
            return false;

        }