cfquery to queryExecute:if if SQL string

时间:2016-07-27 15:52:47

标签: coldfusion cfml lucee

即使在<cfquery>

中,我在queryExecute中所做的最佳方式是什么?

CFQUERY

<cfquery name="qry">
    SELECT * FROM tbl_products
    WHERE filed1 = 1

    <cfif structKeyExists(URL, "test")>
        AND filed2 = 2
    </cfif>

    ORDER BY id DESC
</cfquery>

cfexecute

<cfscript>

    sql = "
        SELECT * FROM tbl_products
        WHERE filed1 = 1
        ORDER BY id DESC
    ";

    if (structKeyExists(URL, "test")){
        sql = "
            SELECT * FROM tbl_products
            WHERE filed1 = 1
            AND filed2 = 2
            ORDER BY id DESC
        ";
    }

    qry = queryExecute(
        sql = sql
    );

</cfscript>

我希望我能很好地解释自己......

1 个答案:

答案 0 :(得分:6)

您必须构建SQL字符串。同样非常值得传递param值,这样就可以防止SQL注入。类似的东西:

<cfscript>
params = {};

sql = "
    SELECT * FROM tbl_products
    WHERE filed1 = :filed1 
";
params["filed1"] = 1;

if (structKeyExists(URL, "test")){
    sql &= "AND filed2 = :filed2 ";
    params["filed2"] = 2;
}

sql &= "ORDER BY id DESC";

queryExecute(sql, params);
</cfscript>

或者,您可以使用位置参数。

<cfscript>
params = [];

sql = "
    SELECT * FROM tbl_products
    WHERE filed1 = ?
";
arrayAppend(params, 1);

if (structKeyExists(URL, "test")){
    sql &= "AND filed2 = ? ";
    arrayAppend(params, 2);
}

sql &= "ORDER BY id DESC";

queryExecute(sql, params);
</cfscript>

这是标签优于脚本的时代之一。