db_foreach sql code_block argsWhat it does:
Performs the SQL query $sql, executing $code_block once for each row with variables set to column values.Defined in: /web/philip/packages/acs-core/10-database-procs.tclExample:
db_foreach "select foo, bar from greeble" { ns_write "<li>foo=$foo; bar=$bar\n" } if_no_rows { # This block is optional. ns_write "<li>No greebles!\n" }
Source code:
if { [llength $args] != 0 } { if { [llength $args] != 2 || (![string equal [lindex $args 0] "else"] && ![string equal [lindex $args 0] "if_no_rows"]) } { error "db_foreach called incorrectly: second argument must be 'else' or 'if_no_rows' and followed by another code block" } } db_with_handle db { set selection [ns_db select $db $sql] set counter 0 while { [ns_db getrow $db $selection] } { for { set i 0 } { $i < [ns_set size $selection] } { incr i } { upvar [ns_set key $selection $i] column_value set column_value [ns_set value $selection $i] } uplevel $code_block incr counter } if { $counter == 0 && [llength $args] == 2 } { uplevel [lindex $args 1] } }