JSON解析:来自PHP5(攻击数据库:mySQL)ios5 iphone

发布于 2024-12-23 02:21:45 字数 3827 浏览 2 评论 0原文

我希望有人可以帮助我,因为我一整天都在尝试:((新东西)

我有一个数据库mySQL,其中包含一个表“产品”(两行:“id”和“stock”)。 我希望我的 ios5 应用程序发送一个“id”并接收该产品的“库存”。

在我的 PHP 代码中:

echo json_encode(array(
     'id'=>$id,
     'stock'=>$stock, ));

我相信它会向我的应用程序发送一个 JSON,我的应用程序在一个名为: 的函数中接收此 JSON,

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    NSString *responseStringWEB = [request responseString];
    NSLog(@"STRING:: %@ \n", responseStringWEB); //3
    NSDictionary *responseDict = [responseStringWEB JSONValue];
    NSLog(@"DICT: %@ \n", responseDict); //3
    NSString *id_producto = [responseDict objectForKey:@"id"];
    NSString *stock = [responseDict objectForKey:@"stock"];
    NSLog(@"ID: %@\n", id_producto); //3
    NSLog(@"stock: %@", stock); //3
}

并检查我得到的控制台:

**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado
2011-12-26 18:58:57.170 CaeDeCajon[1998:16403] Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x984aeb0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`DICT`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`ID`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`stock`**: (null)

问题是:我不知道 JSON 是什么格式(数组,如何我应该解析 NSstring responseStringWEB 来获取这两个值( ID 和 STOCK )吗?我似乎从数据库中收到了它们,但我无法提取它们

:)谢谢,

编辑::

谢谢。这确实有帮助。

看来这与我在 PHP 代码中使用的多重回显有关。现在我只有一个echo,以json格式发送数据。它与我的数据库和应用程序完美配合:我收到所有商品的整个表(“id”和“stock”)。谢谢。

但我发现了另一个障碍(难怪),就是产品售出后我需要更改数据库,并且由于它们通常不会 1 对 1 出售,因此必须将数组发布到 PHP 中,我的目的是发布受影响的产品/商品的 id 和 reductor(reductor 代表该“id”的产品已售出数量)(array_id 和 array_reductor)。

IOS5 代码:

NSArray *array_id=[[NSArray alloc]initWithObjects:@"0",@"3",@"5", nil]; 

//带有 id 产品;

NSArray *array_reductor=[[NSArray alloc]initWithObjects:@"10",@"5",@"40", nil];

//与已售产品的数量(所以我必须将数据库中的先前库存数量减去这些才能获得当前的库存数量)。

NSURL *url=[[NSURL alloc]initWithString:@"http://www.haveyourapp.com/promos/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:array_id forKey:@"id"];
[request setPostValue:array_reductor forKey:@"reductor"];

[request setDelegate:self];
[request startAsynchronous];

我的 PHP 文件:

if (isset($_POST['id'])&&isset($_POST['reductor'])) // 检查数据是否到来 {

$id = array();          // I create arrays
$reductor = array();

$id=$_POST['id'];             // and store arrays in them ( At least is what I believe )
$reductor=$_POST['reductor'];

$connection = new createConnection(); //i created a new object
$connection->connectToDatabase(); // connected to the database
$connection->selectDatabase();

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// Stock reduction in the items affected////////////////////////////////


$num=mysql_numrows($id);
$i=0;
$stock_anterior=array();
while ($i < $num) {

$query=" SELECT  stock FROM productos WHERE id = $id[$i]";
$stock_anterior[$i] = mysql_query($query);
++$i;
}


$l=0;

$num2=mysql_numrows($id);

while ($l < $num2) {

$stock_reductor[$l] = $stock_anterior[$l] - $reductor[$l];

$query = "UPDATE productos SET stock = '$stock_reductor[$l]' WHERE id = $id[$l] ";
mysql_query($query);


++$l;

}



$connection->closeConnection();

但我的代码无法正常工作,我不知道问题是出在我的应用程序中还是 PHP 文件中(可能),但是我如何接收这两个数组并使用它们???

预先感谢

我在堆栈溢出上花了很多时间:非常有用!!!!!!

I hope someone can help me put because I've trying the whole day :( ( newly stuff )

I have a database mySQL, which contains one table "products" ( two rows : "id" and "stock" ).
And I want my ios5 app to send an "id" and receive the "stock" of that product.

In my PHP code:

echo json_encode(array(
     'id'=>$id,
     'stock'=>$stock, ));

Which I believe sends a JSON to my app, my app receives this JSON in a function called:

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    NSString *responseStringWEB = [request responseString];
    NSLog(@"STRING:: %@ \n", responseStringWEB); //3
    NSDictionary *responseDict = [responseStringWEB JSONValue];
    NSLog(@"DICT: %@ \n", responseDict); //3
    NSString *id_producto = [responseDict objectForKey:@"id"];
    NSString *stock = [responseDict objectForKey:@"stock"];
    NSLog(@"ID: %@\n", id_producto); //3
    NSLog(@"stock: %@", stock); //3
}

and checking the console I get:

**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado
2011-12-26 18:58:57.170 CaeDeCajon[1998:16403] Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x984aeb0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`DICT`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`ID`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`stock`**: (null)

The question is : I do not know what format the JSON is coming ( array, How should I parse the NSstring responseStringWEB to get those two values ( ID and STOCK ). It seems I receive them from the database but I do not reach to extract them.

HELP :) thank you ,

EDITING::

Thanks. It really Helped.

It seemed that there has had something to do with the multiple echos I used in the PHP code. Now I only have one echo, sending data in json format. It works perfectly with my database and my app: I receive the whole table ( "id" and "stock" ) of all items. Thanks.

But I have found another obstacle ( no wonder ), is that I need to change the database once the products have been sold, and as they´re not usually sold 1 by 1 must post arrays into PHP,, my intention is to POST the id and reductor(reductor represent how many products of that "id" were sold ) of the products/items affected ( array_id and array_reductor).

IOS5 CODE:

NSArray *array_id=[[NSArray alloc]initWithObjects:@"0",@"3",@"5", nil]; 

//with the id products;

NSArray *array_reductor=[[NSArray alloc]initWithObjects:@"10",@"5",@"40", nil];

//with the number of products sold ( so I have to decrease the previous stock number in the database by these to obtain the current stock numbers ).

NSURL *url=[[NSURL alloc]initWithString:@"http://www.haveyourapp.com/promos/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:array_id forKey:@"id"];
[request setPostValue:array_reductor forKey:@"reductor"];

[request setDelegate:self];
[request startAsynchronous];

MY PHP FILE:

if (isset($_POST['id'])&&isset($_POST['reductor'])) // check if data is coming
{

$id = array();          // I create arrays
$reductor = array();

$id=$_POST['id'];             // and store arrays in them ( At least is what I believe )
$reductor=$_POST['reductor'];

$connection = new createConnection(); //i created a new object
$connection->connectToDatabase(); // connected to the database
$connection->selectDatabase();

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// Stock reduction in the items affected////////////////////////////////


$num=mysql_numrows($id);
$i=0;
$stock_anterior=array();
while ($i < $num) {

$query=" SELECT  stock FROM productos WHERE id = $id[$i]";
$stock_anterior[$i] = mysql_query($query);
++$i;
}


$l=0;

$num2=mysql_numrows($id);

while ($l < $num2) {

$stock_reductor[$l] = $stock_anterior[$l] - $reductor[$l];

$query = "UPDATE productos SET stock = '$stock_reductor[$l]' WHERE id = $id[$l] ";
mysql_query($query);


++$l;

}



$connection->closeConnection();

But my code is not working, I don not know if the problem is in my app or in the PHP file ( likely ), but how can I receive those two arrays and work with them????

Thanks in advance

I spend a lot of time on stack Overflow: VERY USEFULLLLLLLL!!!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你げ笑在眉眼 2024-12-30 02:21:45

json_encode 仅适用于 UTF-8 编码的数据,因此当找到无效字符时,它会全部返回 NULL。

检查您的数据是否采用 UTF-8 编码。

另请检查您的文件是否使用 UTF-8。

json_encode 的替代方案:

// función interna: comprueba si un array es puro o no
// es puro si sus índices son: 0, 1, 2, ..., N
function aputio($a) {
    $i=0;
    foreach ($a as $n=>$v) {
        if (strcmp($n,$i)) return(true);
        $i++;
    }
    return(false);
}

// cambiar quotes, \n y \r para devolver cadenas válidas JSON
function qcl2json($qcl) {
    return str_replace('"','\"',str_replace("\n",'\n',str_replace("\r",'\r',$qcl)));
}

// devolver variable en formato json
function ajson($av,$level=0,$utf8=false) {
    if (($av===null) && !$level) return("null");
    if (!is_array($av)) return (gettype($av)=="integer"?$av:'"'.($utf8?utf8_encode($av):$av).'"');
    $isobj=aputio($av);
    $i=0;
    if (!$level) $e=($isobj?"{":"["); else $e="";
    foreach ($av as $n=>$v) {
        if ($i) $e.=",";
        if ($isobj) $e.=(is_numeric($n) && !is_string($n)?$n:"\"".qcl2json($utf8?utf8_encode($n):$n)."\"").":";
        if (!is_array($v)) {
            if (is_bool($v)) $e.=($v?"true":"false");
            else if ($v==NULL) $e.='""';
            else if (is_int($v)||is_double($v)) $e.=$v;
            else $e.='"'.qcl2json($utf8?utf8_encode($v):$v).'"';
        } else {
            $e.=(count($v)
                ?(aputio($v)
                    ?"{".ajson($v,$level+1)."}"
                    :"[".ajson($v,$level+1)."]")
                :"{}");
        }
        $i++;
    }
    if (!$level) $e.=($isobj?"}":"]");
    return($e);
}

如果可以使用 UTF-8,请避免使用此函数。

json_encode works only with UTF-8 encoded data, so when find a invalid character, it returns NULL for all.

Check your data is encoded in UTF-8.

Also check your file is using UTF-8.

An alternative to json_encode:

// función interna: comprueba si un array es puro o no
// es puro si sus índices son: 0, 1, 2, ..., N
function aputio($a) {
    $i=0;
    foreach ($a as $n=>$v) {
        if (strcmp($n,$i)) return(true);
        $i++;
    }
    return(false);
}

// cambiar quotes, \n y \r para devolver cadenas válidas JSON
function qcl2json($qcl) {
    return str_replace('"','\"',str_replace("\n",'\n',str_replace("\r",'\r',$qcl)));
}

// devolver variable en formato json
function ajson($av,$level=0,$utf8=false) {
    if (($av===null) && !$level) return("null");
    if (!is_array($av)) return (gettype($av)=="integer"?$av:'"'.($utf8?utf8_encode($av):$av).'"');
    $isobj=aputio($av);
    $i=0;
    if (!$level) $e=($isobj?"{":"["); else $e="";
    foreach ($av as $n=>$v) {
        if ($i) $e.=",";
        if ($isobj) $e.=(is_numeric($n) && !is_string($n)?$n:"\"".qcl2json($utf8?utf8_encode($n):$n)."\"").":";
        if (!is_array($v)) {
            if (is_bool($v)) $e.=($v?"true":"false");
            else if ($v==NULL) $e.='""';
            else if (is_int($v)||is_double($v)) $e.=$v;
            else $e.='"'.qcl2json($utf8?utf8_encode($v):$v).'"';
        } else {
            $e.=(count($v)
                ?(aputio($v)
                    ?"{".ajson($v,$level+1)."}"
                    :"[".ajson($v,$level+1)."]")
                :"{}");
        }
        $i++;
    }
    if (!$level) $e.=($isobj?"}":"]");
    return($e);
}

Avoid using this functions if you can use UTF-8.

橘亓 2024-12-30 02:21:45

您的 json 编码是正确的,请尝试将此行添加到您的 php 脚本中,因为 IOS 可能对响应非常严格。

将其添加到您的 php 脚本中:

header('Content-type: application/json');

除此之外,还要检查您是否匹配参数的大小写。我看到您的 php 脚本发送了 id 但看起来您的 ios 脚本正在寻找 ID

your json encoding is correct try add this line to your php script because IOS may be really strict with the response.

add this to your php script:

header('Content-type: application/json');

besides that check you are matching the case of your parameters. I see your php script sends id but looks like your ios script is looking for ID

秋心╮凉 2024-12-30 02:21:45

使用 HTTPScoop 等工具检查 PHP 脚本输出。根据控制台输出,我怀疑出现了问题,其中包含行 ConnectionbuiltDatabase selected..Connection returnedDeconectado...

**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado

看起来您已经得到了一些在 JSON 开始之前打印的脚本中的日志记录,iOS 端的 JSON 解析器不接受该脚本。

Check the PHP script output using a tool such as HTTPScoop. I suspect that something is wrong, based on the console output, which contains the lines Connection establishedDatabase selected.. and Connection closedDesconectado...

**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado

It looks like you've got some logging from that script that is printed before the JSON starts, which isn't accepted by the JSON parser on the iOS end.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文