Apologies for ambiguous title
Given the following data..
+------+------------+--------+
| ID | value | used |
+------+------------+--------+
| 1001 | 1 | 0 |
+------+------------+--------+
| 1002 | 1 | 0 |
+------+------------+--------+
| 1003 | 2 | 0 |
+------+------------+--------+
| 1004 | 4 | 0 |
+------+------------+--------+
| 1005 | 1 | 0 |
+------+------------+--------+
| 1006 | 1 | 0 |
+------+------------+--------+
| 1007 | 1 | 0 |
+------+------------+--------+
| 1008 | 6 | 0 |
+------+------------+--------+
I would like to set the sum value of say 8, so the result would be ....
+------+------------+--------+
| ID | value | used |
+------+------------+--------+
| 1001 | 1 | 1 |
+------+------------+--------+
| 1002 | 1 | 1 |
+------+------------+--------+
| 1003 | 2 | 1 |
+------+------------+--------+
| 1004 | 4 | 1 |
+------+------------+--------+
| 1005 | 1 | 0 |
+------+------------+--------+
| 1006 | 1 | 0 |
+------+------------+--------+
| 1007 | 1 | 0 |
+------+------------+--------+
| 1008 | 6 | 0 |
+------+------------+--------+
I would do this my going through each item adding it to a total value, similar to this
$goal = 8;
$select = "SELECT ID, value FROM table WHERE !used";
$result = mysql_query($select);
while ($row = mysql_fetch_array($result))
{
$total = $total + $row['value'];
if ($total => $goal)
{
$over = $goal - $total
if ($over)
{
$id = $row['id'];
mysql_query("INSERT INTO table(value,used) VALUES('$over',0)");
mysql_query("update table SET used = 1 WHERE id = '$id'")
}
break;
}
$id = $row['id'];
mysql_query("update table SET used = 1 WHERE id = '$id'")
}
So, pretty ugly. suggestions of a better method?