Skip to main content
Participating Frequently
February 24, 2007
Answered

CFQuery inside of a loop

  • February 24, 2007
  • 4 replies
  • 603 views
Can anyone show me the most efficient way of wrapping loops around a query? I have a multi-select form field being passed through the URL scope. The table I need to query looks like this:

region_id region_name
1 Africa
2 Asia
etc.

The variable url.region is passing the region_name and I need to do a lookup of the region_id through a query. Since this is a multi-select, there can be many regions in the variable. The code below doesn't yet loop and so only returns 1 value even if the url.region contains 2 or more values. Can anyone describe the best way of getting this to work?

<cfif IsDefined('url.region')>
<cfset regnList2 = ListQualify(url.region,"'",",","all")>

<cfquery name="GetRegionID" datasource="#myDB#">
select region_id from region
where region_name IN (#PreserveSingleQuotes(regnList2)#)
</cfquery>

</cfif>

Many thanks in advance!

Dave
    This topic has been closed for replies.
    Correct answer
    Do not use a loop for this!

    The attached code should work.

    4 replies

    Correct answer
    February 25, 2007
    Do not use a loop for this!

    The attached code should work.

    HoserDaveAuthor
    Participating Frequently
    February 25, 2007
    That did the trick. Thanks a bunch Mike!!!

    Dave
    Inspiring
    February 25, 2007
    Change the form to get rid of the quotes.

    On your action page, try using cfqueryparam with the list attribute set to yes.
    HoserDaveAuthor
    Participating Frequently
    February 25, 2007
    Dan,

    url.region looks like 'Africa' if single selected, or 'Africa','Asia' if multi-selected. At least that's what shows up in a cfdump. Region_id is an integer type column.

    I should note that the actual url.region comes in as 'Africa,Asia' when multi-selected but I'm using ListQualify to create the single tick list for use in the IN clause for the query. Not sure if that makes a difference in the solution here. More precisely, url.region would still be 'Africa,Asia' but I'm putting that into regionList2 as value 'Africa','Asia'.

    What I'm trying for is pretty much the following:

    <cfif IsDefined('url.region')>
    <cfset regionList2 = ListQualify(url.region,"'",",","all")>
    <cfset regionList3 = ''>
    <cfloop index="i" from="1" to="#ListLen(regionList2)#">
    <cfquery name="GetRegionID" datasource="#myDB#">
    select region_id from region
    where region_name IN (#PreserveSingleQuotes(regionList2(trying to put bracket i close bracket here))#)<!---THIS is problem area--->
    </cfquery>
    <cfset regionList3 = regionList3 & '#GetRegionID.region_id#'>
    </cfloop>
    </cfif>

    Thanks for the response and huge thanks in advance if you can help on this :).

    Dave
    Inspiring
    February 24, 2007
    What exactly does url.region look like? Also, is region_id a numeric or char field in your db?