简体   繁体   中英

JSON data sent from objective-C not updating in sql table

I have a program with a function to run when the program starts and I am sending data via JSON to my database. It looks for a url that runs a PHP script to insert the JSON data into the database and it is working perfectly. My issue is that when the program closes and runs the decontructor and calls the update.php script that it does not update my table row and instead adds a new row to the table without any data being changed. My console response shows the correct JSON data being sent in each respective constructor/deconstructor so I know the correct data is being sent. Any help that could point me in the right direction as to why my rows are not being updated would be greatly appreciated.

Objective-C Contructor

NSString *strURL = @"mysite.com/insert.php";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if ( request != nil ) {
    NSDictionary *dict = @{ @"IP"           : [self GetIP],
                            @"UUID"         : [self GetUUID],
                            @"isActive"     : @1};


    NSError *error;

    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];

    NSString *jsonData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    NSData *requestData = [NSData dataWithBytes:[jsonData UTF8String]
                                         length:[jsonData lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];

    [request setHTTPMethod:@"POST"];
    //[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:requestData];

    // Send a synchronous request
    NSURLResponse * response = nil;
    NSError * NSURLRequestError = nil;

    NSData * responseData = [NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&NSURLRequestError];
    if ( responseData != nil ) {
        NSLog(@"responseData is valid.");

        NSString *myString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
        NSLog(@"myString:\t%@", myString);
    } else {
        NSLog(@"responseData is nil!");
    }
} else { // uh oh
    NSLog( @"Error creating the URL request!" );
}

Insert.php (php script called from constructor) - WORKS PERFECTLY

<?php

$host = "localhost";
$userid = "root";
$password ="password";
$database = "database"; 

// read JSON input

$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);

$request_data = json_decode($raw_post_data, true);

print_r($request_data);
// prepare header for reply

header("Content-Type: application/json");

// open database

$mysqli = new mysqli($host, $userid, $password, $database);

// check connection 

if ($mysqli->connect_errno) {
echo json_encode(array("success" => false, "message" => $mysqli->connect_error, "sqlerrno" => $mysqli->connect_errno));
exit();
}

// perform the insert

$sql = "INSERT INTO table (IP,UUID,isActive) VALUES (?,?,?);";

if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ssi", $request_data["IP"], $request_data["UUID"], $request_data["isActive"]);

    if (!$stmt->execute())
    $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate);
else
    $response = array("success" => true);

$stmt->close();
} else {
$response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate);
}

Now I have the exact same code for the Deconstructor when the program close. The only difference is the url calls a different php script to do the UPDATE and "isActive" is changed to 0.

Deconstructor

NSString *strURL = @"mysite/update.php";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if ( request != nil ) {
    NSDictionary *dict = @{ @"IP"           : [self GetIP],
                            @"UUID"         : [self GetUUID],
                            @"isActive"     : @0};


    NSError *error;

    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];

    NSString *jsonData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    NSData *requestData = [NSData dataWithBytes:[jsonData UTF8String]
                                         length:[jsonData lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];

    [request setHTTPMethod:@"POST"];
    //[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:requestData];

    // Send a synchronous request
    NSURLResponse * response = nil;
    NSError * NSURLRequestError = nil;

    NSData * responseData = [NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&NSURLRequestError];
    if ( responseData != nil ) {
        NSLog(@"responseData is valid.");

        NSString *myString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
        NSLog(@"myString:\t%@", myString);
    } else {
        NSLog(@"responseData is nil!");
    }
} else { // uh oh
    NSLog( @"Error creating the URL request!" );
}

Update.php (php script called in deconstructor)

$host = "localhost";
$userid = "root";
$password ="password";
$database = "database"; 

// read JSON input

$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);


// prepare header for reply

header("Content-Type: application/json");

// open database

$mysqli = new mysqli($host, $userid, $password, $database);

// check connection 

if ($mysqli->connect_errno) {
echo json_encode(array("success" => false, "message" => $mysqli->connect_error, "sqlerrno" => $mysqli->connect_errno));
exit();
}

$request = json_decode($raw_post_data,true);

print_r($request);

foreach(json_decode(raw_post_data, true) as $item)
{
    $IP       = $item['IP'];
    $UUID     = $item['UUID'];
    $isActive = $item['isActive']; 

$query = "UPDATE table SET isActive= ?  WHERE IP = ? AND UUID = ? ";
$statement = $mysqli->prepare($query);

$results = $statement->bind_param('sss', $isActive, $IP, $UUID);
$results = $statement->execute();
}


$mysqli->close();

In the INSERT statement isActive is an integer. In the UPDATE it's a string even though you're sending it as a number with @0

$results = $statement->bind_param('sss', $isActive, $IP, $UUID);

Should be: $results = $statement->bind_param('iss', $isActive, $IP, $UUID);

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM