2012-03-08 17 views
6

我的目標是隻輸出在「fieldList中」指定的列數據。試圖輸出查詢時獲得複雜的對象錯誤值

得到以下錯誤:

Complex object types cannot be converted to simple values. The expression has requested a variable or an intermediate expression result as a simple value, however, the result cannot be converted to a simple value. Simple values are strings, numbers, boolean values, and date/time values. Queries, arrays, and COM objects are examples of complex values. The most likely cause of the error is that you are trying to use a complex value as a simple one. For example, you might be trying to use a query variable in a cfif tag. The error occurred on line 20.

當試圖做到以下幾點:

<cfquery datasource="retailers" name="myQuery"> 
Select * FROM retailer 
WHERE retailer_id = '#url.id#' 
</cfquery> 

<cfset fieldList = "company,phone,phone_secondary,fax,email,website"> 
<cfloop list="#fieldList#" index="i">  
#myQuery[i]# 
</cfloop> 

不應該這項工作沒有給我一個錯誤?我覺得我只是俯瞰簡單的東西我不能在任何地方找到答案。

+0

澄清:你是否試圖從查詢結果中輸出列名稱列表?或者你只是想做最明顯的 - 這是:循環查詢的結果(即所有的數據行)並輸出它們。我問,因爲你沒有具體說明*你想要什麼*,並且代碼(如書面)可能以任何方式。 – 2012-03-08 23:09:22

回答

8

好吧,我看你ammended您最初的代碼,所以這裏是我的迴應:

您遍歷列的列表,並試圖就好像它是一個結構單一的元素來評估每個列。

的查詢,但是,是稍有不同:它是作爲一系列結構的,這反過來,是數組訪問 - 因爲他們從查詢返回的數據的每一行的。

如果你想輸出的所有數據行的,不知道的列在前面(或通過他們的動態,你在上面的代碼中暗示),試試這個:

<cfoutput query="myQuery"> 
    <cfloop list="#myQuery.ColumnList#" index="thisColumn"> 
    #myQuery[thisColumn][myQuery.CurrentRow]# 
    </cfloop> 
</cfoutput> 

這將爲您提供所需的輸出。外CFOUTPUT與查詢屬性將循環在你收到的所有數據行。然後,對於每一行,您循環查詢生成的列列表,併爲每列輸出數據,通過myQuery.CurrentRow指定行,該行通過外部輸出自動迭代。

我還需要一些時間,現在提倡大家儘量循環內環路遠離,只是輸出自己的價值觀明確:

<cfoutput query="myQuery"> 
    #company# #phone# 
</cfoutput> 

使用這個語法要稍微比上述循環更便宜在一個循環內。

+0

非常詳細和真棒的答案!謝謝Shawn,非常感謝! – timsayshey 2012-03-09 14:09:17

相關問題