去年,我发布了一个问题here,该问题有关提交50个字段的表单以及执行此操作的最佳方法。该解决方案仍在使用中,并且效果很好。但是,要构建这些动态查询,最后要重复很多<cfif>,我想知道是否有更好的方法来处理此问题。虽然代码以“ messy”结尾,但是由于这个原因,db当然很干净,并且写入次数也保持最小,但是还有更好的方法吗?

<cfif StructKeyExists(arguments.form,"data1") or StructKeyExists(arguments.form,"data2") or StructKeyExists(arguments.form,"data3")>
  <cfquery>
    insert into table1 (
      <cfif StructKeyExists(arguments.form,"data1")>data1,</cfif>
      <cfif StructKeyExists(arguments.form,"data2")>data2,</cfif>
      <cfif StructKeyExists(arguments.form,"data3")>data3,</cfif>
      userid
    )
    values (
      <cfif StructKeyExists(arguments.form,"data1")><cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.form.data1#" maxlength="30">,</cfif>
      <cfif StructKeyExists(arguments.form,"data2")><cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.form.data2#" maxlength="10">,</cfif>
      <cfif StructKeyExists(arguments.form,"data3")><cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.form.data3#" maxlength="25">,</cfif>
      <cfqueryparam cfsqltype="cf_sql_smallint" value="#arguments.form.userid#" maxlength="5">
    )
    on duplicate key update
      <cfif StructKeyExists(arguments.form,"data1")>data1=values(data1),</cfif>
      <cfif StructKeyExists(arguments.form,"data2")>data2=values(data2),</cfif>
      <cfif StructKeyExists(arguments.form,"data3")>data3=values(data3),</cfif>
      userid=values(userid)
  </cfquery>
</cfif>


由于某种原因,这种“感觉”是错误的。例如,更明智的做法是进行更多写入,将每个值拆分为自己的更新,如下所示:

<cfif StructKeyExists(arguments.form,"data1")>
  <cfquery>
    insert into table1 (data1,userid)
    values (<cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.form.data1#" maxlength="30">,<cfqueryparam cfsqltype="cf_sql_smallint" value="#arguments.form.userid#" maxlength="5">)
    on duplicate key update data1=values(data1),userid=values(userid)
  </cfquery>
</cfif>


等等

还是有一种更好的方法可以完全忽略我呢?

最佳答案

如果您知道您有多达50个字段,并且它们都被一致地命名(data1 ... dataN),那么我将只有一个循环。就像是:

<cfloop index="i" from="1" to="50">
    <cfif StructKeyExists(arguments.form, "data#i#")>
        <cfquery>
            insert into table1 (data#i#,userid)
            values (<cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.form['data' & i]#" maxlength="30">,<cfqueryparam cfsqltype="cf_sql_smallint" value="#arguments.form.userid#" maxlength="5">)
            on duplicate key update data#i#=values(data#i#),userid=values(userid)
        </cfquery>
    </cfif>
</cfloop>

09-27 21:29