![](/img/trans.png)
[英]ios5 & JSON: can retrieve data from php file but cannot send to the database
[英]JSON parsing: from PHP5 ( which attacks a database: mySQL ) ios5 iphone
我希望有人可以幫助我,因為我已經嘗試了一整天:((新東西)
我有一個數據庫mySQL,其中包含一個表“products”(兩行:“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”)。 謝謝。
但是我發現了另一個障礙(難怪),一旦產品售出后我需要更改數據庫,並且由於它們通常不會逐個銷售,必須將數組發布到PHP中,我的意圖是POST 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文件中(可能),但我怎樣才能收到這兩個數組並使用它們?
提前致謝
我花了很多時間在堆棧上溢出:非常有用了!!!!!!
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編碼是正確的嘗試將此行添加到您的PHP腳本,因為IOS可能對響應非常嚴格。
將此添加到您的PHP腳本:
header('Content-type: application/json');
除了那個檢查,你匹配你的參數的情況。 我看到你的PHP腳本發送id
但看起來你的ios腳本正在尋找ID
使用HTTPScoop等工具檢查PHP腳本輸出。 基於控制台輸出,我懷疑出現了問題,其中包含Connection closedDesconectado
Connection establishedDatabase selected..
的行Connection establishedDatabase selected..
和Connection closedDesconectado
...
**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado
看起來你已經從JSON啟動之前打印的那個腳本中獲得了一些日志記錄,這在iOS端的JSON解析器上是不被接受的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.