2012-03-20 96 views
0

我再次遇到了PHP,並具有以下更新代碼。這工作,但只爲最後一個插入?我需要更新所有gritem ID。我認爲將[]添加到不唯一的表單字段允許PHP將其解析爲數組,但它仍然將其視爲一個字段?在PHP中使用相同表單名稱的多行更新

我的HTML我有:

<input type="hidden" name="gritemid[]" value="<?PHP echo $row2['gritemid']; ?>"> 
<input type="text" name="grqty[]" id="grqty[]" value="" /> 

下面的PHP代碼

if(isset($_POST['storageloc'])) 
{ 
    //Set the GRQTY to subtract from the Orderqty on each item in the list if selected 
    // find out how many records there are to update 
    $size = count($_POST['gritemid']); 

    // start a loop in order to update each record 
    $i = 0; 
    while ($i < $size) { 
     // define each variable 
     $gritemid= $_POST['gritemid'][$i]; 
     $grqty= $_POST['grqty'][$i]; 
     if ($grqty > "0") { 
      // do the update and print out some info just to provide some visual feedback 
      $query = "UPDATE gr_items SET orderqty = orderqty - $grqty WHERE gritemid = '$gritemid' LIMIT 1"; 
      mysql_query($query) or die ("Error in query: $query"); 
     } 
     ++$i; 
    } 
    mysql_close(); 
+0

通過執行print_r($ _ POST)開始查看所得結果。沒有看到任何明顯的錯誤。 id =「grqty []」需要消失,因爲id應該是唯一的。但它不應該造成任何傷害,除非你有一些JavaScript正在進行。 – Cerad 2012-03-20 19:58:18

回答

0

首先,你真的應該做你的帖子的一些驗證/禁制拖放到查詢之前瓦爾。同時作爲瓦爾您使用的似乎是整數,我會建議使用intval() -

// define each variable 
$gritemid = intval($_POST['gritemid'][$i]); 
$grqty = intval($_POST['grqty'][$i]); 

如果更換您的來電的mysql_query()與print($query);你看到了多個查詢,你會期待什麼呢?

+0

這似乎是伎倆,不知道爲什麼差異只是添加intval?我猜對方被視爲一個字符串,因此被忽略? – 2012-03-20 20:10:20

相關問題