2009-10-29 35 views
2

使用Results.columnname如何打印所有的結果,而不ColdFusion的如何打印所有的結果,而不在ColdFusion中

使用Results.columnname爲前: -

<cfquery name="getProductId"> select productId from product </cfquery>

在產品表我有2列與product_name和Product_id。

我怎樣才能打印出來,而無需使用 getProductId.product_name getProductId.Product_id

感謝,

回答

5

你想達到什麼目的?如果你正在尋找一種方式來計算方式基於查詢其列,你不知道名字,如輸出查詢結果...

<cfquery name="queryName" ...> 
    select * from product 
</cfquery> 

...那麼你可以使用queryName.ColumnList變量,它返回一個逗號分隔所有列名稱的列表。隨後可以遍歷該列表,並根據需要輸出。

例如,爲了得到一個簡單的HTML表格輸出:

<table border=1> 
    <cfloop from="0" to="#queryName.RecordCount#" index="row"> 
     <cfif row eq 0> 
      <tr> 
       <cfloop list="#queryName.ColumnList#" index="column" delimiters=","> 
        <th><cfoutput>#column#</cfoutput></th> 
       </cfloop> 
      </tr> 
     <cfelse> 
      <tr> 
       <cfloop list="#queryName.ColumnList#" index="column" delimiters=","> 
        <td><cfoutput>#queryName[column][row]#</cfoutput></td> 
       </cfloop> 
      </tr> 
    </cfif> 
    </cfloop> 
</table> 

道歉,如果這不是你的意思!

+0

再次說明,不需要這個「行」變量!移動循環外的thead部分,然後執行查詢cfloop! –

+0

@彼得 - 好點! –

+0

@Chris在這個如何才能提取出單列信息?我的意思是它是給我輸出作爲行明智,其中包含單行的每一列,我如何提取一行的所有列? –

2

能否請你澄清什麼意思「而無需使用列名」?

也許你想使用getProductId.ColumnList屬性?從我的舊代碼轉換查詢到的陣列(有點剝離細節和改變變種名稱,但給出了這個概念)

小例子:

<cfset arrRecordSet = ArrayNew(1)> 

    <cfloop query="qGetSomething"> 
     <cfset record = StructNew()> 
     <cfloop list="#qGetSomething.ColumnList#" index="field"> 
      <cfset record[field] = qGetSomething[field][qGetSomething.CurrentRow]> 
     </cfloop> 
     <cfset ArrayAppend(arrRecordSet,record)> 
    </cfloop> 

編輯:增強的例子來擺脫連續可變的,正如註釋中正確注意到的。

+0

不需要「行」變量。當做一個查詢循環時,你已經有了'QueryName.CurrentRow'變量已經是 –

+0

@Peter,你是對的。這就是爲什麼我告訴它它是「舊代碼」的一部分:) – Sergii

1

爲了擴大我對克里斯的答覆意見,這裏的簡單版本與缺失THEAD/TBODY標籤說:

<cfoutput> 
    <table> 
     <thead> 
      <tr> 
       <cfloop index="ColName" list="#MyQuery.ColumnList#"> 
        <th>#ColName#</th> 
       </cfloop> 
      </tr> 
     </thead> 
     <tbody> 
      <cfloop query="MyQuery"> 
       <tr> 
        <cfloop index="ColName" list="#MyQuery.ColumnList#"> 
         <td>#MyQuery[ColName][MyQuery.CurrentRow]#</td> 
        </cfloop> 
       </tr> 
      </floop> 
     </tbody> 
    </table> 
</cfoutput>