Pergunta

I would like to provide optional arguments to a ColdFusion Component using only CFScript, while maintaining use of the ColdFusion QueryParam SQL.

EXAMPLE A: Retrieving information from a basic user.cfm for all users:

<cfset get = application.controller.getuser()>

EXAMPLE B: Optionally, using the same method. Retrieving information from a basic user-edit.cfm?edit=662B2709-0BA3-42DB-AD2CC29069F4A259 for a specific user:

<cfset get = application.controller.getuser( userUID=url.edit )>

EXAMPLE C: Alternately, using the same method to find a specific first name:

<cfset get = application.controller.getuser( firstname=form.firstname )>

CFC ISSUE: Below is my controller.cfc. I would like to maintain the "AND userUID = :userUID" as an optional CFQueryParam that appears when requested only when requested by my script.

public function getuser( userUID='', password='', firstname='' ){
    var get = new query();

    // query
    get.setSQL("
        SELECT  *
        FROM    users
        WHERE   1 = 1
        AND     userUID = :userUID
        AND     firstname = :firstname
        AND     passhash = :password
        ");

    if ( len(arguments.userUID) > 0 )
        get.addParam( name = "userUID", value = "#arguments.userUID#", cfsqltype = "cf_sql_varchar" );      

    if( len(arguments.firstname) > 0 )
        get.addParam( name = "firstname", value = "#arguments.firstname#", cfsqltype = "cf_sql_varchar" );

    if ( len(arguments.password) > 0 )
        get.addParam( name = "password", value = "#arguments.password#", cfsqltype = "cf_sql_varchar" );

    return get.execute();
}
Foi útil?

Solução

Something like this should get you started.

sqlString = "select * from users where 1 = 1 ";
if ( len(trim((arguments.userUID)) > 0 )
sqlString &= " AND     userUID = :userUID";
etc

get.setSQL(sqlString);

Note that with this answer the query will return the entire table if no arguments are provided. That's also the case for your original code. You might want to think about handling that situation.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top