Skip to main content
September 22, 2011
Question

Array in Where clause?

  • September 22, 2011
  • 4 replies
  • 6300 views

I would like to create a Coldfusion function where one of my arguments is and array of "user_id"'s. Then I want to:

Select * from database where (each id in the array) = #user_id#

How is this written?

This topic has been closed for replies.

4 replies

BKBK
Community Expert
Community Expert
September 25, 2011

@C-Rock

Should you be interested, the clause where the fuss is all about is:

WHERE id IN (<CFQUERYPARAM VALUE="#IDList#" CFSQLTYPE="CF_SQL_INTEGER" LIST="yes">)

I have assumed the user IDs are whole numbers.

BKBK
Community Expert
Community Expert
September 24, 2011

C-Rock wrote:

I would like to create a Coldfusion function where one of my arguments is and array of "user_id"'s. Then I want to:

Select * from database where (each id in the array) = #user_id#

How is this written?

<cffunction name="getDetails" returntype="query">

    <cfargument name="userIDs" type="array">

    <cfset var IDList = arrayToList(userIDs)>

    <cfquery name="details" datasource="myDSN">

    SELECT *

    FROM myTable

    WHERE id IN (#IDList#)

    </cfquery>

    <cfreturn details>

</cffunction>

Inspiring
September 24, 2011

   WHERE id IN (#IDList#)

Do not forget to use cfqueryparam to avoid sql injection. Also remember to scope query variables too.

BKBK
Community Expert
Community Expert
September 25, 2011

-==cfSearching==- wrote:

   WHERE id IN (#IDList#)

Do not forget to use cfqueryparam to avoid sql injection. Also remember to scope query variables too.

I would disagree. If there is a need to use cfqueryparam here, then the design is likely improper.

User IDs don't usually come from users themselves. One may therefore assume that, by the time we arrive at an in-process like this one, the IDs have been validated and are kosher (or halal, as the case may be).

Dileep_NR
Inspiring
September 23, 2011

Hi,

Please try this,

Select * from database where user_id in( <cfqueryparam cfsqltype="cf_sql_integer"  list="true" value="#arraytoList(useridarray)#">)

Inspiring
September 22, 2011

Use a WHERE IN clause.  You can use the arrayToList() function to generate the list of user id's.

      http://www.w3schools.com/SQl/sql_in.asp

Inspiring
September 23, 2011

Better yet, create a list instead of an array to start with.  Less processing that way.