开发者

ColdFusion Conditional RecordCount

Alright SO users... Here's a seemingly impossible to go wrong conditional statement. It is very simple, however, I cannot figure out why it won't work the way it is expected to.

<cfoutput query="checkForAd">
        <!--- also used the line <cfif RecordCount eq 0> --->
    <cfif checkForAd.RecordCount eq 0>
        <!--- Display some message. (Perhaps using a table, undecided) --->
    <cfelse>
        <!--- Display some other message. (Happens to be a table) --->
    </cfif>
</cfoutput>

When the RecordCount returns a number greater than 0, the else case displays properly. When RecordCount开发者_如何学运维 returns 0, nothing is displayed and the form continues along its path. I've become very frustrated as this should be quite simple...


The output won't return any results if the query set is empty. Try:

<cfif checkForAd.RecordCount eq 0>
    <!--- Display some message. (Perhaps using a table, undecided) --->
<cfelse>
    <cfoutput query="checkForAd">
        <!--- Display some other message. (Happens to be a table) --->
    </cfoutput>
</cfif>

I assume that you're looking to return a number of records... if you were just returning one, the query="checkForAd" isn't necessary. You can simply reference the query & variables in a <cfoutput></cfoutput>.

Edit

Here's one way to access a query variable: QueryName["ColumnName"][RowNum]

(As you look to expand your coding, there's a lot you can do with query variables. There's a great rundown of the different approaches at ColdFusion and getting data from MySQL)


As nykash has pointed out, the body of a cfoutput query (or a cfloop query) never executes if there are no records, so doing a check for a zero recordcount will never be true inside of one.

However, I find the following example a more readable one:

<cfif NOT checkForAd.RecordCount >
    <!--- Display some message. --->
</cfif>

<cfoutput query="checkForAd">
        <!--- loop through data --->
</cfoutput>

It might not seem much in isolation, but I think it's a bit cleaner and easier to see what's going on, especially when combined with other code.

Specifically on the RecordCount check, if I care about the specific number then I'll use EQ (or NEQ/GT/etc) but if I only care about "having records" vs "not having records" then I use the implicit boolean conversion that CFML provides to simplify the code. This really makes it easier to identify when I'm using the common binary choice or a more significant one, so navigating through the code is easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜