从PHP数组更新mysql数据库中的值

时间:2012-03-05 11:22:14

标签: php mysql arrays sorting multidimensional-array

我正在查询数据库,将结果值插入到数组中然后操作它们,之后我想使用数组中的mysql_update更新受影响行中的每个值,这是我遇到麻烦的地方。

这是我的代码 - 请帮助:

name   sellerid quantity
-------------------------
john       12     10
joel       23     20
brian      40     10

让我们将其作为查询结果,并且有人现在订购了25个项目,该程序将采取这些项目并将其分配给订购者然后从卖家中扣除。

$cursor="SELECT itemquantity,sellerid FROM mytable WHERE  price='$price'";                     
//it is a table containing data about people selling their commodities

$foundItems = array();

// likely to be a parameter of a function...
$totalUnitsOrdered = 25;

// maps user to amount assigned from him
$assignedQuantityPerUser = array();


while ( $row = mysql_fetch_assoc( $cursor ) ) {

  // Still order Quantity left?
  if ( 0 < $totalUnitsOrdered ) {

    if ( $row[ "itemquantity" ] <= $totalUnitsOrdered ) {
      if (!isset($assignedQuantityPerUser[$row["sellerid"]])) {
        $assignedQuantityPerUser[$row["sellerid"]] = 0;
      }

      // assign all of $row[ "itemquantity" ]
      $totalUnitsOrdered  -= 0 + $row[ "itemquantity" ];
      $assignedQuantityPerUser[ $row[ "sellerid" ] ] += 0 + $row[ "itemquantity" ];

    }  else {
      // assign all the rest: $totalUnitsOrdered
      $totalUnitsOrdered   = 0;
      $assignedQuantityPerUser[ $row[ "sellerid" ] ] += $totalUnitsOrdered;
    }
  }

  $newItem[] = $row[ "sellerid" ];
  $newItem[] = $row[ "itemquantity" ];

  // Append $newItem to the end of $foundItems 
  $foundItems[] = $newItem;
}

1 个答案:

答案 0 :(得分:1)

有三种情况(算法) 这是伪代码不是确切的代码我希望你能得到这个想法

while($row= mysql_fetch_assoc($rec))
{
  if(quantity for user is  > total quantity ordered)
  {
    quantity of user -=total quantity ordered 
    update tableNamse set qty =quantity for user where userId=$row['id'];
    exit while
  }
  else if(quantity for user = total quantity ordered)
  {
     quantity of user=0;
    update tableNamse set qty =0 where userId=$row['id'];
    exit while
  }
  else
  {
     total quantity ordered - = quantity of user
    update tableNamse set qty =0 where userId=$row['id'];
    continue while loop
  }
 }

- 更新

   if($row['itemquantity'] > $totalUnitsOrdered)
   {
     $qtyUser=$row['itemquantity']-$totalUnitsOrdered;
     mysql_query("update tableName set itemQuantity=$qtyUser
                  where userId=$row['userId']" )
      break; // exit while
   } 

- 第三种情况的更新

  else
{
$totalUnitsOrdered-=$row['itemquantity'];
mysql_query("update tableName set itemQuantity=0
                  where userId=$row['userId']" )

}