Using StructKeyExists instead of IsDefined

To improve the code, we are going to convert all calls to isDefined() to structKeyExists() . A few things I need to know are:

How to define a query in structKeyExists() ? For instance:

 <cfquery name="getname" datasource="dsn">select * from table</cfquery> <cfif isDefined('getname') and getname.recordcount neq "">Do this</cfif> 

Since scope is not defined for isDefined() , what scope should be used for structKeyExists() ?

+6
source share
2 answers

The default scope is variables, so StructKeyExists(variables,"getname") will do your check.

However, if there is no missing logic in the above example, you do not need the isDefined / StructKeyExists check, because if you run the query, it will always be determined, just without any lines, so your second check, getname.recordcount should be enough.

+12
source

This is an old question, but for posterity.

 <cfquery name="getname" datasource="dsn"> select * from table </cfquery> <cfif getname.recordcount>Do this</cfif> 

cfif getname.recordcount works like a logical check. If nothing happens in the result set, it fails ... if it returns a record, which satisfies the boolean check.

To deploy. Suppose we select a specific field of type id , and we want to provide output for any condition:

It will look like this:

 <cfquery name="getname" datasource="dsn"> select id from table </cfquery> <cfif getname.recordcount> <cfoutput query="getname"> #id#<br> </cfoutput> <cfelse> No records found. </cfif> 
0
source

All Articles