0

即使在_ _<cfquery>queryExecute

查询

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

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

    ORDER BY id DESC
</cfquery>

cf执行

<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>

我希望我已经很好地解释了自己...

4

1 回答 1

6

您必须建立 SQL 字符串。同样值得传递参数值,这样您就可以免受 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>

这是标签比脚本更好的时代之一。

于 2016-07-27T17:16:24.540 回答