从iOS应用程序搜索数据库并显示此信息


Search a database from an iOS application and display this information

我需要从iOS应用程序搜索数据库并显示此信息。我试过这个代码:

NSString *myRequestString = [[NSString alloc] initWithFormat:@"type=%@",  type];
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:@"http://localhost:8888/search.php"]];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
//NSLog(@"responseData: %@", content);
NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding];
这是我的php代码:
 <?php
//Your database host server
$db = "ELE";
$type= $_POST["type"];  
 //echo $type;
$connect=mysql_connect("localhost:8888","root","root");
if(!$connect)
{
    die("Database server connection failed.");  
}
else
{
    //Attempt to select the database
    $dbconnect = mysql_select_db($db, $connect);
    //Check to see if we could select the database
    if(!$dbconnect)
    {
        die("Unable to connect to the specified database!");
    }
    else
    {
        ////echo "type";
        $query = "select *from ele where type='$type'";
        //echo $query;
        $resultset = mysql_query($query, $connect);
        $records = array();
        //Loop through all our records and add them to our array
        while($r = mysql_fetch_assoc($resultset))
        {
            $records[] = $r;    
        }
        //Output the data as JSON
        echo json_encode($records, JSON_UNESCAPED_UNICODE);
    }
}
mysqli_close($connect);
?>

输入的字符串将在查询中使用,但这不起作用。

我想以JSON格式返回查询结果。变量类型打印在调试NSLog。当我在php中通过Post和echo接收它时,它是空的。

我期望查询返回JSON并由php localhost页面显示。

如果你不能使用mysqli,那么不要混合使用它们。最后一行是mysqli_close($connect);

你的代码看起来像这样:

<?php
$json = array();
if(isset($_POST['type']){
    $type= $_POST["type"]; 
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");
    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s'n", $mysqli->connect_error);
        exit();
    }
    if ($stmt = $mysqli->prepare("SELECT * FROM ele WHERE type=?")) {
        /* bind parameters for markers */
        $stmt->bind_param("s", $type);
        /* execute query */
        if($stmt->execute()){
            $records = array();
            /* fetch associative array */
            while ($row = $stmt->fetch_assoc()) {
                $records[] = $row; 
            }
            /* close connection */
            $mysqli->close();
            $json['success'] = true;
            $json['records'] = $records 
        }else{
            $json['success'] = false;
            $json['message'] = 'failed to SELECT';        
        }
    }
}else{
    $json['success'] = false;
    $json['message'] = 'type is not set';
}
echo json_encode($json);
?>

至于解析JSON数据,你只需要序列化它,这样你就可以访问它们,确保你记录了一切。

编辑:

如果你的代码仍然有问题,你可以试试:

-(NSData *)post:(NSString *)postString url:(NSString*)urlString{
    //Response data object
    NSData *returnData = [[NSData alloc]init];
    //Build the Request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    //Send the Request
    returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
    //Get the Result of Request
    NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
    bool debug = YES;
    if (debug && response) {
        NSLog(@"Response >>>> %@",response);
    }

    return returnData;
}

用法:

NSString *postString = [NSString stringWithFormat:@"type=%@",type];
NSString *urlString = @"https://www.yourapi.com";
NSData *returnData =  [self post:postString url:urlString];
NSDictionary *jsonData = [[NSDictionary alloc]init];
if (returnData !=nil) {
    NSLog(@"responseData: %@", returnData); 
    jsonData = [NSJSONSerialization JSONObjectWithData:returnData 
                                               options:NSJSONReadingMutableContainers 
                                                 error:nil];
    bool success = [jsonData[@"success"] boolValue];
    if(success){
       NSArray *records = jsonData[@"records"];
       NSLog(@"records = %@", records);
    }else{
        NSString *error = jsonData[@"message"];
        NSLog(@"error = %@", error);
    }
}else{
    NSLog(@"responseData is nil"); 
}