gpt4 book ai didi

php - Array/Dict 从 Xcode 到 JSON 到 PHP 到 mySql

转载 作者:行者123 更新时间:2023-11-29 03:13:30 27 4
gpt4 key购买 nike

这让我抓狂。它看起来很简单,而且我可能遗漏了一些明显的东西 - 并且强烈怀疑这是因为我缺乏 PHP/mysql 技能,但我无法让它工作。我在其他地方仔细查看(并窃取了)许多来自 StackOverflow 的代码片段,试图解决这个问题,但我仍然不相信我已经成功了。

在 Xcode 中,我尝试将 NSDictionary 对象编码为 JSON(使用 JSON 框架),以便我可以使用 PHP POST 方法将数组动态存储在 mysql 中(理想情况下作为单个扁平对象 - 我知道,我知道)。

代码如下。我可以创建 json ok。我可以正常连接,我可以更改不是数组变量且不需要通过 json 发送的变量,我几乎可以做任何事情。我似乎无法传递该 json 并将其存储在 mysql 中。

是的-我是菜鸟。

谢谢...

我已经走到这一步了:

在 xcode 中

NSDictionary *loginDict = [NSDictionary dictionaryWithObjectsAndKeys:
@"aname", @"username",
@"hello", @"password",
nil];


NSString *jsonString = [loginDict JSONRepresentation];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *post = [NSString stringWithFormat:@"json=%@", jsonString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

[request setURL:[NSURL URLWithString:@"http://domain.com/post_dict.php"]];
[request setHTTPMethod:@"POST"];

[request setHTTPBody:postData];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

在 post_dict.php

<?php

$rawJsonData = $_POST['json'];
$decodedData = json_decode($rawJsonData); //do i even need to decode if i want to store a flattened json object in mysql?


//Connect To Database
$hostname='**BLACKEDOUT**.com';
$username='**BLACKEDOUT**';
$password='**BLACKEDOUT**';
$dbname='**BLACKEDOUT**';
$usertable='users';
//I want to update the Records field with the array
$recordsfield = 'Records';


mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);


$query = "UPDATE $usertable SET $recordsfield = '$decodedData' ";//do i encode? serialize? dunno

$result = mysql_query($query);


if(!$result)
{
mysql_close();
echo mysql_error();
return;
}

mysql_close();


?>

最佳答案

如果您使用 POST 方法发送 JSON,则可以使用以下代码在 PHP 中接收它

<?php $handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);
?>

关于php - Array/Dict 从 Xcode 到 JSON 到 PHP 到 mySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4411967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com