how to loop through Query Columns in ColdFusion - coldfusion

I have a query in a my CFC. The function contains a simple query as such.
<cfquery name="qrySE" datasource=#mydatasource#>
SELECT
NAMES,SALARY
FROM tblTest
</cfquery>
I want to display my resultset as such (horizontally):
NAME1 NAME2 NAME3 NAME4
10 20 45 62
Is there a way to loop through the columns of my query and create a virtual query for this purpose?
If anyone has done this, please let me know.

Just wanted to add Al Everett's solution returns the columns back in alphabetical order. If you would like to get the column names back in the same order as the query you can use:
ArrayToList( qrySE.getColumnNames() )
which I found here: http://www.richarddavies.us/archives/2009/07/cf_columnlist.php
you can use this to create a function to output queries to a table like this:
<cffunction name="displayQueryAsTable" output="true">
<cfargument name="rawQueryObject" type="query" required="true">
<table >
<tr>
<cfloop list="#ArrayToList(rawQueryObject.getColumnNames())#" index="col" >
<th>#col#</th>
</cfloop>
</tr>
<cfloop query="rawQueryObject">
<tr>
<cfloop list="#ArrayToList(rawQueryObject.getColumnNames())#" index="col">
<td>#rawQueryObject[col][currentrow]#</td>
</cfloop>
</tr>
</cfloop>
</table>
</cffunction>

You could use the built-in query.columnList that is returned with each query. (It's metadata of the query, like recordCount.)
You could do something like this:
<table>
<cfloop list="#qrySE.columnList#" index="col">
<tr>
<cfloop query="qrySE">
<td>#qrySE[col][currentRow]#</td>
</cfloop>
</tr>
</cfloop>
</table>
Not tested, but that should give you the idea.

Related

Avoid duplicate with nested cfoutput and cfloop

I have made a dynamic form that combines a list of individuals. In this list, I have a field that contains the values of a dynamic list. My concern is that this field (#id_p#_state) is multiplied by the initial query and I want to avoid that. the result I have is for example if I have 10 results in the first query, each line of the second is x10
<cfinvoke component="cfc_query" method="methode_h" returnvariable="result">
<cfinvokeargument name="id_atser" value="#id#">
</cfinvoke>
<cfinvoke component="cfc_query" method="methode_state" returnvariable="result_state">
</cfinvoke>
<cfoutput query="result">
<tr>
<td>#lastname# #firstname# #id_personne#</td>
<cfloop from="1" to="#daysInMonth(createdate(datepart('yyyy',now()),form.date_periode,1))#" index="boucle">
<td><cfinput name="#id_personne#_date_presence" type="text" value="#dateformat(createdate(datepart('yyyy',now()),form.date_periode,boucle),'dd/mm/yyyy')#" size="7"></td>
<td>
<cfselect name="#id_p#_state" style="width: 32px;">
<cfloop query="result_state">
<cfoutput>
<option value="#id_state#">#description#</option>
</cfoutput>
</cfloop>
</cfselect>
</td>
</cfloop>
</tr>
</cfoutput>
You have a CFOUTPUT nested inside of a CFOUTPUT loop.
Get rid of the redundant CFOUTPUT around your option tag and this should clean up your output.

CF SQL Creating a Table with different results

I am trying to create a table using coldfusion and sql. The table I am trying to create looks like this:
<cfquery datasource="#application.dsn#" name="someprocessTable">
SELECT *
FROM checklists
</cfquery>
<table id="Checklist_Stats">
<thead>
<th><b>Associate Name</b></th>
<th><b>Location</b></th>
<th><b>Checklists Generated by Associate</b></th>
<th><b>Checklists Generated by Selected Location(s)</b></th>
<th><b>Associate Percentage of Location Total</b></th>
</thead>
<tbody>
<cfoutput query="someprocessTable">
<tr>
<td>#associate#</td>
<td>#location_code#</td>
<td>#associate.recordcount#</td>
<!---<td>##</td>
<td>##</td>--->
</tr>
</cfoutput>
</tbody>
</table>
The part I am unsure about is how do I loop all of this information under one table? Because you would not want to have the same persons name keep reoccurring on the table and then how do you show how many was generated by them since I could not do something like #associate.recordcount#
There seems more than one way to do what you want to achieve like doing a query with joins and groups then dump in table; manage your output with a single CFoutput or use nested CFOutput and/or CFloop.
Following show third approach:
<table border="1" id="Checklist_Stats">
<thead>
<th><b>Associate Name</b></th>
<th><b>Location</b></th>
<th><b>Checklists Generated by Associate</b></th>
<th><b>Checklists Generated by Selected Location(s)</b></th>
<th><b>Associate Percentage of Location Total</b></th>
</thead>
<tbody>
<cfquery name="allAssociatesQry" dbtype="query">
SELECT DISTINCT associate, COUNT(*) AS associateCount FROM someprocessTable GROUP BY associate ORDER BY associate
</cfquery>
<cfloop query="allAssociatesQry">
<cfquery name="allLocCodeForAssociateQry" dbtype="query">
SELECT * FROM someprocessTable WHERE associate='#associate#' ORDER BY location_code
</cfquery>
<tr><td><cfoutput>#allLocCodeForAssociateQry.associate#</cfoutput></td>
<cfoutput query="allLocCodeForAssociateQry" group="location_code">
<cfset locCntr = 0 />
<cfoutput>
<cfset locCntr = locCntr + 1 />
</cfoutput>
<cfif allLocCodeForAssociateQry.currentRow NEQ 1>
<tr><td> </td>
</cfif>
<td>#allLocCodeForAssociateQry.location_code#</td>
<td>#allAssociatesQry.associateCount#</td>
<td>#locCntr#</td>
<td>#Round((locCntr/allAssociatesQry.associateCount) * 100)#%</td>
</tr>
</cfoutput>
</cfloop>
</tbody>
</table>
Please note that CF QoQ is case sensitive so if need be then convert associate name and location to lower/upper/title case before hand
A slightly modified code for the CFloop may be like below:
<cfloop query="allAssociatesQry">
<cfset thisAssociateName = trim(allAssociatesQry.associate) />
<cfquery name="allLocCodeForAssociateQry" dbtype="query">
SELECT location_code,count(location_code) AS locCntr FROM someprocessTable WHERE associate='#thisAssociateName#' GROUP BY location_code ORDER BY location_code
</cfquery>
<cfoutput query="allLocCodeForAssociateQry">
<tr>
<td>#thisAssociateName#</td>
<td>#allLocCodeForAssociateQry.location_code#</td>
<td>#allAssociatesQry.associateCount#</td>
<td>#allLocCodeForAssociateQry.locCntr#</td>
<td>#Round((allLocCodeForAssociateQry.locCntr/allAssociatesQry.associateCount) * 100)#%</td>
</tr>
<cfset thisAssociateName = "" />
</cfoutput>
</cfloop>

ColdFusion form - display error details from database table

I have a database table with error id and error details for form validation errors.
In my ColdFusion form page, I have a list of error numbers 2,4,7 available. But I want to display errors like "Please enter name" etc.
I want to compare my list of errors with error id's in the database table and display the corresponding error in my form. Please let me know if there is any better way to do it. Thanks in advance!!
<form name = "empform" action="empform.cfm" method="post">
<cfoutput>
<table border="0">
<tr><td colspan="4" align="center" style="padding-bottom:20px;"><h2>Add Employee</h2></td></tr>
<cfif (structKeyExists(rc,"addemp"))>
<cfif rc.result.hasErrors()>
<tr>
<td colspan="4" style="border:2px solid red;">
Please review the following:
<ul>
<cfloop array="#rc.result.getFailureMessages()#" index="message">
<li>#message#</li>
</cfloop>
</ul>
</td>
</tr>
</cfif>
</cfif>
<cfset myArray = rc.result.getFailureMessages()>
<cfset myList = ArrayToList(myArray, ",")>
<cfquery name="qErrorMessages" datasource="#dsn#" >
Select * from ErrorMessages
</cfquery>
<tr>
<td><label><b>Emp Last Name</b></label></td>
<td><input name="lastname" type="text" value="" /></td>
<td><label><b>First Name</b></label></td>
<td><input name="FirstName" type="text" value="" /></td>
</tr>
<tr>
<td><label><b> Emp Birth Date</b></label></td>
<td><input name="birthdate" type="text" value="" /></td>
<td><label><b>Salary</b></label></td>
<td><input name="salary" type="text" value="" /></td>
</tr>
<tr><td style="padding-top:10px;">
<input type="submit" name = "addemp" value ="AddEmp /></td>
</tr>
</table>
</cfoutput>
</form>
I can display errors as shown above
Now I want to show actual messages. I am stuck up here.
My issue is not solved. I am able to loop through the table of errors only. Probably I need to loop through my list of error ids and then I need another loop to look up for the table errorId's to match then display the error.
I got it fixed with the below code.
<cfloop index="ind" list=#mylist#>
<cfquery datasource= "#dsn#" name="emperrors">
Select errorid,errmessage from errorcodes where errorid = #ind#
</cfquery>
#emperrors.errmessage#<br>
</cfloop>
Your question is short on details, but I'd probably query the table with the error messages, convert it to a struct, then drop that struct into a persistent scope that I could then reference later.
Something like:
<cfset errorStruct={}>
<cfloop query="qFormErrorMsgs">
<cfset errorStruct[error_id]=error_msg>
</cfloop>
<cfset application.errorStruct=errorStruct>
Then, when you want to display the error:
<p>Please fix the following error: #application.errorStruct[variables.error_id]#</p>
But that's just one way you might do it. Without more information in your question all you're going to get is guess (if you're lucky).
Alright, your answer detailing code should have been appended to your question via an edit, and still that's really not enough code. How are you determining your errors?
It sounds like your errors are something like this:
Please review the following:
2
3
6.
When what you want is error messages.
An easy way to update this is to load all your messages into an array where the index corresponds to the error codes.
<cfset ErrDetails=ArrayNew()>
<cfset ErrDetails[1]="You didn't enter your first name.">
<cfset ErrDetails[2]="You didn't enter your last name.">
<cfset ErrDetails[3]="You didn't enter a properly formatted birth date.">
<cfset ErrDetails[4]="It appears, from your birthdate, that your age is below 18">
And then, in your cfloop, you can
<cfloop array="#rc.result.getFailureMessages()#" index="message">
<li>#ErrDetails[message]#</li>
</cfloop>
Lastly it sounds like your errorcodes/messages are coming from a database. I'm not really sure that's necessary, but if you really want to keep it that way, that's fine. You can initialize this into the application scope so that you can call it later without rerunning the query, or just put it somewhere in flat text. However, if you want the application scope answer, here's a method.
<cflock scope="application" timeout="5">
<cfif not isDefined("application.ErrDetails")>
<cfquery name="getec">
select ErrID,ErrMessage from ErrorCodes
</cfquery>
<cfset Application.ErrDetails = []>
<cfloop query="getec">
<cfset Application.ErrDetails[ErrID]=ErrMessage>
</cfloop>
</cfif>
<cfset request.ErrDetails = Application.ErrDetails>
</cflock>
Once this is initiated, the cfloop displaying errors as I showed above can use #request.errDetails[message]#
If it's just running in one page, I wouldn't worry about creating an application variable. I'd just hardcode it in, or do a query there with a cfloop similar to above writing to a variables scope variable, not an application variable so the cflock isn't needed.
Unless you also have web based admin creating these rules, I'd probably ditch the table altogether and drop it directly into code, a cfinclude, a udf, or a custom tag.
Since the asker has updated their question with an answer.
Your answer needlessly repeats the query for each iteration.
Try something like this..
<cfquery datasource="#dsn#" name="GetECs">
select ErrorID,ErrMessage from ErrorCodes
where ErrorID in (<cfqueryparam cfsqltype="cf_sql_integer" list="yes" value="#mylist#">)
</cfquery>
<cfoutput query="GetECs">
#currentrow#. #ErrMessage#<br>
</cfoutput>
Notes:
One query is run.
For results, the where ErrorID in (<cfqueryparam cfsqltype="cf_sql_integer" list="yes" value="#mylist#">) is the same as saying where ErrorID in (#mylist#). However, the tag secures your queries against sql injection (the tactic of modifying variables to produce undesirable/malicious results in a query. Read up on cfqueryparam at http://help.adobe.com/livedocs/coldfusion/8/htmldocs/help.html?content=Tags_p-q_18.html

Need advice.. dynamic td tr

Hi am doing dynamic TR and TD in coldfusion, but apparently i am trying this kind of screen. here is my try with colfusion
<cfif variables.newrow EQ true>
<tr align="center">
</cfif>
<cfoutput query="gResults">
<cfquery datasource="#request.dsn#" name="nextqueries">
Query
</cfquery>
<td height="30" valign="middle"><strong>
<a href="viewdir.cfm?catID=#val(pic_id)#
<cfif isDefined('url.l') and url.l neq ''>&l=#url.l#</cfif>">
#pic_cat_name#</a></strong><br>
<cfloop query="nextqueries">
<cfquery datasource="#request.dsn#" name="showanother">
select * from
mytable as grlist
where pic_cid =
<cfqueryparam cfsqltype="cf_sql_numeric" value="#Trim(nextqueries.pic_id)">
</cfquery>
»
<a href="viewdir.cfm?catID=#val(pic_id)#
<cfif isDefined('url.l') and url.l neq ''>&l=#url.l#</cfif>">#pic_cat_name#
</a> </cfloop></td>
<cfif gResults.currentRow MOD 4 EQ 0>
</tr>
<cfset variables.newrow = true>
<cfelse>
<cfset variables.newrow = false>
</cfif>
</cfoutput>
trying to do like this:
http://screencast.com/t/oso4jkhBm3
There are a lot of potential improvements, but this answer will only deal with table rows. You start with:
<cfif variables.newrow EQ true>
<tr align="center">
</cfif>
Now I'm going to look for the closing tag. The only one I see is here:
<cfif gResults.currentRow MOD 4 EQ 0></tr></cfif>
and that line is inside a query loop. What this means is that you might have more than one closing tag, or you might not have any. You need exactly one. To solve this specific problem, you have to do this:
<cfif variables.newrow EQ true>
<tr align="center">
code to populate this table row
</cfif>
When you get that part sorted out, we can look at what goes into the details.
To get data to display in an html table from top to bottom then left to right like in the image linked in your question, you can do something similar to the following.
<!--- Get query results --->
<cfset arrayOFValues = arraynew(1)>
<cfset queryResults = querynew("Col1,Col2,Col3")>
<!--- Fill query with example data --->
<cfloop from="1" to="25" index="i">
<cfset queryaddrow(queryResults)>
<cfset querySetCell(queryResults, "Col1", "Col1 Row " & i)>
<cfset querySetCell(queryResults, "Col2", "Col1 Row " & i)>
<cfset querySetCell(queryResults, "Col3", "Col1 Row " & i)>
</cfloop>
<!--- Now have a query named queryResults with 25 rows --->
<!--- Set the number of columns and calculate the number of rows needed --->
<cfset numberOfColumns = 3>
<cfset rowsNeeded = ceiling(queryResults.recordcount / numberOfColumns)>
<cfoutput>
<table>
<cfloop from="1" to="#rowsNeeded#" index="curRow">
<tr>
<cfloop from="0" to="#numberOfColumns-1#" index="curCol">
<td>
#queryResults.Col1[(rowsNeeded * curCol) + curRow]#
</td>
</cfloop>
</tr>
</cfloop>
</table>
</cfoutput>
The first part is just creating a query result. I then find the number of rows that is needed to display the records by dividing the number of results returned in the query by the number of columns to be displayed. The ceiling is required for when the result is not a whole number.
We have to loop each column record with in the row to get the desired index. To find the required index of the field we have to take the row that’s being displayed + the column were on times the the number of rows that will be displayed.
If you know the number of columns you can hard code for them in the following manner and eliminate the inner loop.
<tr>
<td>#queryResults.Col1[3 * rowsNeeded]#</td>
<td>#queryResults.Col1[3 + 1*rowsNeeded]#</td>
<td>#queryResults.Col1[3 + 2*rowsNeeded]#</td>
</tr>

cfloop empty query condition?

I have the following ColdFusion code that is getting information from a database and displaying the results on the homepage. Here's the cfquery code:
<cfquery name="getSchedule" datasource="#APPLICATION.datasource#" dbtype="odbc">
SELECT * FROM SCHEDULE_Days SD
LEFT JOIN SCHEDULE_ScheduledClasses SSC ON SD.day_id = SSC.day_id
LEFT JOIN SCHEDULE_Classes SC ON SSC.class_id = SC.class_id
WHERE SD.day_date = #createODBCDate(now())# AND SSC.schedule_cancelled = 0
ORDER BY SSC.start_time
</cfquery>
and the output code:
<cfoutput>
<cfloop query="getSchedule">
<tr>
<td width="40"> </td>
<td width="74">#lcase(timeFormat(start_time,"h:mm tt"))#</td>
<td width="158">#class_name#</td>
</tr>
</cfloop>
</cfoutput>
The issue is, if there is no data contained within getSchedule (i.e., there are no ScheduledClasses), it displays nothing.
I'm looking for a way to change this so that, in the event that there is no data to display, I can specify a message and code to be shown in its absence.
First just a quick CF tip you can make you code better by doing it this way:
<cfif getSchedule.recordcount GT 0>
<cfoutput query="getSchedule">
<tr>
<td width="40"> </td>
<td width="74">#lcase(timeFormat(getSchedule.start_time,"h:mm tt"))#</td>
<td width="158">#getSchedule.class_name#</td>
</tr>
</cfoutput>
<cfelse>
<p>Empty record message here</p>
</cfif>
The reason I put the query output first is most likely this will happen more than with your empty set message.
<cfif getSchedule.recordcount>
.... do something
</cfif>
Will work just aswell there is no need for gt 0
Use the recordCount to detect whether the query has any record
<cfif getSchedule.recordcount gt 0>
.... do something
</cfif>
<cfif getSchedule.RecordCount>
<table>
<cfoutput query="getSchedule">
<tr>
<td width="40"> </td>
<td width="74">#lcase(timeFormat(start_time,"h:mm tt"))#</td>
<td width="158">#class_name#</td>
</tr>
</cfoutput>
</table>
<cfelse>
<p>There are currently no records</p>
</cfif>