Insert data into remote mysql database by POST method from iOS device

后端 未结 3 1289
故里飘歌
故里飘歌 2021-01-14 20:26

I have 3 values :

  • id
  • name
  • email

I have three UIText field where i can give these input and save these values into

相关标签:
3条回答
  • 2021-01-14 20:31

    I have a problem updating my database in a similar way....

    Sql statements

    <?php
    
    // Create connection
    $con=mysqli_connect("server_name","user_name","user_code","table_name");
    
    // Check connection
    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    
    // This SQL statement selects ALL from the table 'table.name'
    $sql = "SELECT * table_name";
    
    // 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 json_encode($resultArray);
    }
    
    
    $sql = "INSERT INTO table_name (column_name) VALUES('1')";
    
    
    // Close connections
    mysqli_close($result);
    mysqli_close($con);
    ?>
    

    My iOS code

    for (Tickets *items in _feedItems){
        if ([resultText.text isEqual:(id) items.ticketNumber]) {
    
            status.text = @"Match found";
    
     //Contacting database------------------------------
    
            NSString *strURL = [NSString stringWithFormat:@"TicketDate=%@", items.ticketDate];
    
            NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding 
    allowLossyConversion:YES];
            NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:[NSURL URLWithString:@"http://webservice.com"]];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-   
    Type"];
            [request setHTTPBody:postData];
    
    
            NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
            if(conn)
            {
                NSLog(@"Connection Successful");
            }
            else
            {
                NSLog(@"Connection could not be made");
            }
    
    //Contacting database END-------------------------------------------
    
    
            break;
    
    
        }else {
    
            status.text = @"Match not found";
        }
    }
    

    I get a Connection Succesful from the NSLog but there is nothing getting updated in my database.

    I'm trying to manually type in a ticket number with an app, and if that matches with a ticket in the database (it works), then I want the the ticketDate to change from 0 to 1.

    But it does not change :/

    0 讨论(0)
  • 2021-01-14 20:38

    You can use the NSURLSessionDataTask function to post data up to PHP and get a response with JSON.

    - (IBAction)saveButton:(id)sender
    {
    
    NSString *noteDataString = [NSString stringWithFormat:@"name=%@&email=%@", nameTextField.text, emailTextField.text];
    
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mydomain.com/iOS/Tulon/phpFile.php"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[noteDataString dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *dataRaw, NSURLResponse *header, NSError *error) {
    NSDictionary *json = [NSJSONSerialization
                                  JSONObjectWithData:dataRaw
                                  options:kNilOptions error:&error];
    NSString *status = json[@"status"];
    
    if([status isEqual:@"1"]){
    //Success
    
    } else {
    //Error
    
    }
    }];
    
    [dataTask resume];
    }
    

    and you can handle the response in PHP with this code:

    <?php
    if (isset ($_POST["name"]) && isset ($_POST["email"])){
        $name = $_POST["name"];
        $email = $_POST["email"];
    } else {
        $name = "Tulon";
        $email = "tulon@yahoo.com";
    }
    
    // Insert value into DB
    $sql = "INSERT INTO $dbtable (name, email) VALUES ('$name', '$email');";
    $res = mysql_query($sql,$conn) or die(mysql_error());
    
    mysql_close($conn);
    
    if($res) {          
    $response = array('status' => '1');                 
    } else {
    die("Query failed");
    }
    
    echo json_encode($res);
    exit();
    ?>
    

    Hope this helps

    0 讨论(0)
  • 2021-01-14 20:49

    Can you try this? may be it works for you.

    NSString *strURL = [NSString stringWithFormat:@"name=%@&email=%@", nameTextField.text, emailTextField.text];
    
    NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://mydomain.com/iOS/Tulon/phpFile.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    [request setHTTPBody:postData];
    
    
    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    if(conn)
    {
        NSLog(@"Connection Successful");
    }
    else
    {
        NSLog(@"Connection could not be made");
    }
    

    After this implement following methods to get response

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)d
    {
         [self.ask_data appendData:d];
    
    }
    
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    
        NSString *responseText = [[NSString alloc] initWithData:self.ask_data encoding:NSUTF8StringEncoding];
        NSLog(@"response=%@",responseText);
    }
    
    0 讨论(0)
提交回复
热议问题