I have a site with articles that are sometimes written only by one author, and sometimes there are one or two others (but it could be a number even higher). I need to be able to change the byline dynamically based on how many authors are credited in the database. So, for example, Joe Smith wrote an article, with help from Sally Jones and Dave Thomas. The byline should look like this: By Joe Smith, Sally Jones and Dave Thomas Right now I have the code working so that the initial author appears (and his name is linked to his bio page), but the other two authors are being left out. The main author is entered into one field of a web based app, and the other authors are entered into a separate field. The code is selecting and counting the numbers of authors, but something in the math must not be calculating or outputting correctly. Here is the code: <cfset i=0> <cfif #countAuthors# gt 0> <cfoutput><i></cfoutput> </cfif> <cfloop query="getRelatedAuthors"> <cfoutput> <cfif i eq 0>By <cfelse> <cfif i+1 eq #countAuthors#> and <cfelse>, </cfif> </cfif> <a href="/bios/bio.cfm?aid=#AuthorID#">#trim(AuthorName)#</a> </cfoutput> <cfset i=i+1> </cfloop> <cfif #countAuthors# gt 0><cfoutput></i><br /></cfoutput></cfif> Code (markup):
How about something along these lines? <cfsetting enablecfoutputonly="true"> <cfif getRelatedAuthors.recordcount> <cfoutput><span style="font-style:italic;"></cfoutput> <cfloop query="getRelatedAuthors"> <cfif getRelatedAuthors.currentrow EQ 1> <cfoutput>By </cfoutput> <cfelse> <cfoutput>and </cfoutput> </cfif> <cfoutput><a href="/bios/bio.cfm?aid=#AuthorID#">#trim(AuthorName)#</a></cfoutput> <cfif getRelatedAuthors.recordcount GT 1 AND getRelatedAuthors.currentrow NEQ getRelatedAuthors.recordcount><cfoutput>, </cfoutput></cfif> </cfloop> <cfoutput></span></cfoutput> </cfif> <cfsetting enablecfoutputonly="false" /> Code (markup): FWIW, the <cfsetting/> tag is there to control whitespace. Here is the query that I used to test with: <cfset getRelatedAuthors = QueryNew("AuthorId,AuthorName") /> <cfset QueryAddRow(getRelatedAuthors,3) /> <cfset QuerySetCell(getRelatedAuthors,"AuthorId",1,1) /> <cfset QuerySetCell(getRelatedAuthors,"AuthorName","Larry",1) /> <cfset QuerySetCell(getRelatedAuthors,"AuthorId",2,2) /> <cfset QuerySetCell(getRelatedAuthors,"AuthorName","Moe",2) /> <cfset QuerySetCell(getRelatedAuthors,"AuthorId",3,3) /> <cfset QuerySetCell(getRelatedAuthors,"AuthorName","Curly",3) /> Code (markup):
I think you could make this a lot easier: For one thing, don't put a conditional statement around the loop. if there were zero records, it just wouldn't run. <cfoutput query="getRelatedAuthors"> <!---this just gets the correct 'By, comma, or and---> <cfif getrelatedauthors.currentrow is 1> By: <cfelseif getrelatedauthors.currentrow gt 1 and getrelatedauthors.currentrow lt getrelatedauthors.recordcount> , <cfelse> and </cfif> <a href="/bios/bio.cfm?aid=#AuthorID#">#trim(AuthorName)#</a> </cfoutput>