Php 如何在JSON中编码MYSQL响应并在iOS应用程序中解析
我的php有一个名为load的方法。我可以插入一个不同的方法,但当我改变参数以与这个方法对话时,我认为它正确地发送了数据,但它没有显示在我的应用程序上 index.phpPhp 如何在JSON中编码MYSQL响应并在iOS应用程序中解析,php,mysql,ios,json,nsurlrequest,Php,Mysql,Ios,Json,Nsurlrequest,我的php有一个名为load的方法。我可以插入一个不同的方法,但当我改变参数以与这个方法对话时,我认为它正确地发送了数据,但它没有显示在我的应用程序上 index.php function load(){ //Establish connection $con=mysqli_connect("localhost","root","","Mealidea"); // Check connection if (mysqli_connect_errno())
function load(){
//Establish connection
$con=mysqli_connect("localhost","root","","Mealidea");
// Check connection
if (mysqli_connect_errno()){
$errorR['name']="Failed to connect to mysql".mysqli_connect_error();
echo json_encode(errorR);
}
//Perform query
$result = mysqli_query($con,"SELECT * FROM User");
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
//Close connection
mysqli_close($con);
echo json_encode($myjsons);
}
设置请求:
//Get from DB
NSURL*url=[NSURL URLWithString:@"http://localhost/Tutorials/index.php?f=load&key=6dM7V0n5GqYJLTMibQDf2gA2a94h8hbF"];
//URL request
NSURLRequest*request=[NSURLRequest requestWithURL:url];
//Set the connection
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData=[[NSMutableData alloc]init];
}
获得答案:
NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
//If data is nil, then print error
if (data==nil) {
//NSLog(@"%@",error);
}
//Print the data
NSLog(@"%@",data);
//???? how to parse data?
NSDictionary*num=[data valueForKey:@"User"];
您的PHP脚本似乎正在发送一个数组(用JSON编码),但您的Objective-C代码似乎期望一个
NSDictionary
,如下所示:
NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
应该是这样的
NSArray *users = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
然后,您应该能够迭代用户的
NSArray
,并将其显示在UITableView
或类似的内容中。您是在询问如何在应用程序中显示数据吗?我认为在发送和获取数据之间存在错误。在应用程序中,我应该作为字典接收吗?这些数据是如何构造的?(我这周刚读到了PHP)。PHP发送的是字典还是数组?