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

标签 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;
}

最佳答案

共有三种情况(算法) 这是伪代码而不是确切的代码我希望你明白

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']" )

}

关于php - 从 PHP 数组更新 mysql 数据库中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9565775/

相关文章:

php - 如何将 GMT 时区传递给 PHP DateTime 对象?

php 获取变量值并将其以动态方式附加到查询中

PHP mysqli query() 返回 1

mysql - 用于扩展后端的正确架构

python - 我将如何使用 Dask 对 NumPy 数组的切片执行并行操作?

javascript - 如何在没有表单的情况下发布数据

mysql - MySql <> NULL 和 IS NOT NULL 之间的区别

javascript - 如何从node.js中的二维数组中获取随机项

java - 打印范围,如果缺少数字

php - 使用PHP连接远程MySQL错误