Did you know you can access a query without knowing the column names at the time you code? Each ColdFusion query has a property called columnlist. This, obviously, returns the columns of the query. But how do you access the data? Simple, if q is a query and col is one of the columns, then this will return the value at row N:
#q[col][n]#
Now, one thing to remember. ColdFusion allows you to leave off a row number. This is useful for times when you know the query has one row and you just want to grab data from it. However, with bracket notation, you must always use the row number. Don't forget that when you loop over a query, there is a built-in value, "currentRow", that points to, you guessed it, the current row.
Archived Comments
Ray,
Awesome, I am also using my queries in this fashion. My only problem is that I do not yet understand how to use a variable in the [col] part of q[col][n] syntactically. How would you do that?
THX - JJC
I'm not quite sure I get your question - but are you asking how to dynamically get a particular col/row in a query? If so, the syntax is q (the query) [col] (the name of column) and [row] the row obviously.
So if the query Q had a column, age, and you wanted the 3rd row, you would use:
<cfoutput>#q["age"][3]#</cfoutput>
I think Jim might be asking how to use a variable instead of specifying an actual column name.
So you could use something like:
<cfset mycolumn = "age">
<cfoutput>#q[myColumn][3]#</cfoutput>
Is this true in all versions of coldfusion or is there a cf configuration that will override this?
I'm asking because on my workspace server, I am not using the row number and I'm not getting the _Complex object types cannot be converted to simple values._ error ( like I was on my live site) - which was solved with you advice of adding the row number....?
Thanks,
Reuben
Not sure. Personally I just like being anal and putting in the row number so it is explicit. :)