即使在<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>
我希望我能很好地解释自己......
答案 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>
这是标签优于脚本的时代之一。