updating-values-in-a-mysql-database-from-a-php-array

i am querying the database,inserting the resultant values in an array then manipulating them and thereafter i want to update each of values in the affected rows using mysql_update from the array and that’s where i am having trouble.this is my code.kindly assist.

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

let’s take that as the quey result and someone orders 25 items now the program is to take the items and assign them to one who ordered then deduct from the sellers.

[php]$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;
}

[/php]

The easiest way is to just use the SQL “Update” command. You can review that command at this link:
http://www.w3schools.com/php/php_mysql_update.asp

That should work nicely for you. Just UPDATE the record by calling a second query. You would have to build the query inside your While-loop and execute it. So, you would use, $row2 or whatever so you do not mix up your results from the first query. Give it a try, good luck…

Sponsor our Newsletter | Privacy Policy | Terms of Service