Q:

loops in PHP MYSQL to insert accumulated data from one table to new one

I have a table like this:
id  | order_id | code         | 
1   | 2200     | 489512444756 |
2   | 2200     | 489512444756 |
3   | 2200     | 489512444777 |
4   | 2200     | 489512444777 |
5   | 2200     | 489512444777 |
6   | 2201     | 489512444788 |
7   | 2201     | 489512444788 |
8   | 2201     | 489512444777 |

I'm trying to use for loops to fill another table in MySQL with accumulated data (aggregate the codes to provide qty) with the following columns:
id  | order_id  | code        | qty |

The PHP code used to do this as the following:
mysql_select_db($database, $server);
$query_Recordset1 = "SELECT `order_id` FROM stock GROUP BY order_id ";
$Recordset1 = mysql_query($query_Recordset1, $beharserver) or die(mysql_error());

while ($row_orders = mysql_fetch_assoc($Recordset1)){
  foreach ($row_orders as $ord) {
    $query_Recordset2 = "SELECT `order_id`, code, COUNT(id) AS qty FROM stock WHERE `order_id` = '".$ord."' GROUP BY code";
    $Recordset2 = mysql_query($query, $server) or die(mysql_error());
    $row_orders2 = mysql_fetch_assoc($Recordset2);

    foreach ($row_orders2  as $itm) {
      $insert_qty = "INSERT INTO orders_agg (order_id, code, qty) VALUES ( '".$itm[0]."','".$itm[1]."','".$itm[2]."' )";

      $qty = mysql_query($insert_qty, $server) or die(mysql_error());
    }
  } 
}

The code above is not working well, and inserted data in new table are different from what exactly required. 
The inserted data looks like this:
id  | order_id  | code        | qty |
1   | 3         | 6           | 0   |
etc...

A:

You should use one SQL statement to do all work. It is:
INSERT INTO orders_agg 
(SELECT NULL, `order_id`, code, COUNT(*) AS qty FROM stock
      GROUP BY order_id, code)

