开发者

NSDisctionary to mysql database

I have a NSDictionary that looks like this:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Movies", @"Category", @"Swedish", @"Language" , nil];

I'm converting that to a JSON representation, after that, the string looks like this:

{"Category":"Movies","Language":"Swedish"}

I'm uploading that to my server using ASIHTTPRequest (POST-method) and now I want to input this into my database. I'm not getting it to work. I'm using this loop but it inserts both values on both columns:

$decoded = strip开发者_开发知识库_tags(json_decode($_POST['NSDict']));

//Making connection to DB here

foreach ($decoded as $value) {
    $result = mysql_query("INSERT INTO testtable (category, language) VALUES ('".$value."', '".$value."')") or die(mysql_error());

    echo $result;
}

How should I modify my PHP to insert Movies in to category and Swedish into language?

//Thanks!


ok.. this worked:

<?php

$decoded = json_decode($_POST['Hej']);
//echo $decoded->{'Language'};


$link = mysql_connect("localhost","","");
mysql_query("SET NAMES 'utf8'", $link);
mysql_select_db("quizerDB");

foreach ($decoded as $name => $value) {

$value = json_decode(json_encode($value),true);

$result = mysql_query("INSERT INTO testtable (category, language) VALUES ('".$value['Category']."', '".$value['Language']."')") or die(mysql_error());

echo $result;

}

?> 

is there anything here I could do better? missing in security etc.??


if you try print_r($decoded); you can see the structure of the decoded JSON string. I'm assuming that it returns std_object's instead of an array.

I'm guessing you should be able to do $value->category and $value->Language to get the data you want.


if you use this code.

$json = '{"Category":"Movies","Language":"Swedish"}';
$decoded = json_decode($json);

print_r($decoded);

you can see that it returns this.

stdClass Object
(
    [Category] => Movies
    [Language] => Swedish
)

if you foreach through this you will only get "Movies" and and "Swedish" in each loop. you have to make your JSON decode into an array with the stdClass objects if you want to loop through them.

$decoded->Category; and $decoded->Language; will return "Movies" and "Swedish" respectively.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜