While Loops
while repeats a block as long as a condition holds. It is the loop for "until this becomes true" work - keep going until a threshold is crossed, a budget is spent, a queue is drained - where the number of iterations is not known up front. If you are iterating over rows or a range, reach for for instead.
Check, run, repeat
The condition is any boolean expression over variables. The body usually reassigns at least one of them - otherwise the condition never changes. Declare with let once, then reassign with plain $name = ...; note the ; after the closing brace before the next statement:
while tests the condition before each iteration, including the first. If it is false at the start, the body never runs:
Loops that write
The body is not limited to arithmetic - any statement works, including insert, update, and delete. The whole script still runs in one transaction, so every iteration's writes commit together or not at all:
The iteration cap
A condition that never flips would hold its transaction open forever, so the engine refuses: any loop that exceeds 10,000 iterations fails the request, and everything it did is rolled back:
update or insert over a query - rather than a row-at-a-time loop.while or something else?
- --Iterating over query results or a numeric range: for.
- --Exit or skip decisions in the middle of the body, not at the top: loop with break and continue.
- --Everything else on one page: Control Flow overview.
