How to set value from a query to an input textbox - coldfusion

When a user clicks edit of a specific row in a table, I want the input textboxes in the same page to be filled with that row's details. I tried this but it did not work.
<cfquery name="getDataForEdit" datasource="dsn">
select * from usercardetails where id = '#url.id#'
</cfquery>
<cfoutput>
<cfset #form.username# = #getDataForEdit.username#>
</cfoutput>

Try this as an example to get you going....
<cfquery name="getDataForEdit" datasource="dsn">
select * from usercardetails where id = '#url.id#'
</cfquery>
<!---
OPTIONAL IMPROVEMENT: You might change your SQL to use CFQueryParam, this will protect against SQL injection
select * from usercardetails where id = <cfqueryparam cfsqltype="CF_SQL_NUMERIC" value="#url.id#" />
--->
<!---
OPTIONAL FOR DEBUGGING: If you uncomment this block it will show you the results of your query.
<cfoutput><cfdump var="#getDataForEdit#" label="getDataForEdit" expand="No" /><br /></cfoutput>
--->
<cfoutput>
<cfif getDataForEdit.recordcount is 1> <!--- Check that you only get one row back in results --->
<!--- Coldfusion will build forms for you using cfform, but many coders keep away from it, so instead you need to build the HTML of your form yourself. --->
<form action="index.cfm" method="post">
<p><label for="username">Username</label><input type="text" id="username" name="username" value="#getDataForEdit.username#" /></p>
<p><input type="submit" id="butty01" name="butty01" value="Go" /></p>
</form>
<cfelseif getDataForEdit.recordcount is 0> <!--- If no results --->
<p>No records found</p>
<cfelse> <!--- Anything else will mean many results --->
<p>An error occurred (Multiple records with this ID found)</p>
</cfif>
</cfoutput>
I've put comments in the code around some optional improvements.
Also note that...
<cfset #form.username# = #getDataForEdit.username#>
will be causing you problems.
<cfset username = getDataForEdit.username>
Will create/set a variable username equal to the value of the username column in your query. The # tags are not necessary in this context. # prints out the value of a variable, so you could have done this...
<cfset username = "#getDataForEdit.username#">
Which would print the value of the username column into a string of text (the only thing in the string being the value), and the string of text would have been assigned to the variable username.
form
is a reserved word, as it is a structure (it's worth looking up structures) that contains all of the form variable data posted to your page. You can inspect form by using cfdump
<cfoutput><cfdump var="#form#" label="form" expand="No" /><br /></cfoutput>
To print out one of the values inside form you can do
#form.username#
So (and very confusingly when you're a beginner)...
<cfset #form.username# = #getDataForEdit.username#>
Will create a variable with the name that corresponds to the value of the form field username posted to your page, and fill it with the username from your query. You really don't want that.
Keep at it. Once you get a few basic concepts sorted Coldfusion is a lovely language to code in.

Related

Why is cfoutput being ignored?

I have a very simple CFML page as follows:
<cfquery name="qry" datasource="#application.db.source#" username="#application.db.user#" password="#application.db.pass#">
SELECT * FROM changemgmt.rfc WHERE rfc_id = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="0">;
</cfquery>
<cfoutput query="qry">
#qry.RecordCount#
</cfoutput>
My <cfoutput> tag is not working as I would expect. If you were to look at the source code of this page, it would be entirely composed of empty lines. It's as if the <cfoutput> tag is being parsed out by the server. However if I change the code to:
<cfoutput>
#qry.RecordCount#
</cfoutput>
I am using Lucee as my backend CFML engine. Can anyone explain to my why there is a difference?
<cfoutput query="qry"> this is used to loop throw all the rows in the query. If your query result have no rows, the execution will never reach the login with in the <cfoutput query="qry">. But if there are 1+n rows in the result, your code will print the recordcount 1+n times.
In this case if all you want is to print recordcount of the result, then you just need to use <cfoutput>#qry#</cfoutput>
But if you want to print values each row of the query then you can use <cfoutput query="qry">
<cfoutput query="qry">
<div>
<span>#qry.rfc_id#</span>
<span>#qry.name#</span>
...
</div>
</cfoutput>

Can i remove Pagination from external site with cfhttp

I am fetching one website results in my website and if there are any much more records, the pagination is also coming along with it, so it is displaying pagination and records
this is more than a question rather than before i make any try and i do not know where to start
is this possible, can i make infinite pagination of the results through some client side or server side, let me know please thanks
Pagination look like this in the cfhttp.filecontent as:
<TD align="right" width="100"><font class="MainBody">Pages: << 1 2 >> </FONT></TD>
This should work for you. It searches for a TD tag followed by a FONT tag, followed by Pages.. and then searches to the first closing TD.
The result is stored in newfilecontent.
<cfset newfilecontent = REReplaceNoCase(cfhttp.filecontent,"<td.*?><font.*?>Pages.*?<\/td>","","ALL")>
With a more detailed question, what you need is basically a rudimentary spider.
This is only designed to work from the first page of results onward. You can't target this at say, page 3, and get page 2 and page 1's.
<cfhttp...> <!--- initial cfhttp --->
<cfset buildContents = ArrayNew(1)>
<cfset buildContents[1] = ReReplaceNoCase(cfHttp.fileContent,".*<body.*?>(.*)</body>.*","\1","ALL")>
<!--- Quick regex to parse the contents of the body tag out of the cfhttp --->
<cfloop condition="#ReFindNoCase("(http[^""]*?pagenum=\d+)(?="">>>)",currentContent)# gt 0">
<cfset GetNextPage = ReMatchNoCase("(http[^""]*?pagenum=\d+)(?="">>>)",currentContents)>
<cfhttp url="#GetNextPage[1]#"... result="inLoop">
<cfset currentContents = ReReplaceNoCase(inLoop.filecontent,".*<body.*?>(.*)</body>.*","\1","ALL")>
<cfset ArrayAppend(buildContents,REReplaceNoCase(currentContents,"<td.*?><font.*?>Pages.*?<\/td>","","ALL"))>
<cfif ArrayLen(buildContents) gt 10>
<!--- This code is untested, so this is a safety that you can remove or modify. If BuildContents has more than ten elements, it stops the looping. You can remove this cfif or maybe raise the number as a safety net.--->
<cfbreak>
</cfif>
</cfloop>
<cfdump var="#buildContents#">

Check if Category already exist within database in coldfusion

I want to use a bind to another cfm page to check if the database.
The top portion is a query I wrote that i think would work. If the count of Tag is Greater than 0 then the if statement should trigger stating that the Tag has been taken.
I can write the query, but I do not know how to implement it into the logic below it.
This is my bind page:
<cfquery name="TagCheck" datasource="PostBlog">
select Count(Category)
from Categories
where Category = #URL.Category#
</cfquery>
<cfif URL.Category NEQ "">
<cfif Compare(URL.Category, "2") EQ 0>
<span style="color: red;">The Category <cfoutput>#URL.Category#</cfoutput> already exist within the database.</span>
<cfelse>
<cfoutput><span style="color: Green;">#URL.Category# is available</cfoutput>
</cfif>
</cfif>
Firstly, use cfqueryparam when passing dynamic values to your queries, especially so if it's something the users can specify.
Secondly, when using an aggregate function like Count() you need to then specify an alias if you want to use that value later on.
<cfquery name="TagCheck" datasource="PostBlog">
select Count(Category) AS CategoryCount
from Categories
where Category = <cfqueryparam value="#URL.Category#" CFSQLType="CF_SQL_INTEGER">
</cfquery>
Finally, in your logic you should just need to then do:
<cfif URL.Category NEQ "">
<cfif TagCheck.CategoryCount GT 0>
<span style="color: red;">The Category <cfoutput>#URL.Category#</cfoutput> already exist within the database.</span>
<cfelse>
<cfoutput><span style="color: Green;">#URL.Category# is available</cfoutput>
</cfif>
</cfif>

Insert data from form with dynamically named fields

OK. I've done a terrible job of explaining what I'm trying to do. I will try one more time to be more clear.
I have a list of variables that is submitted to a page with a cfquery insert. The variables come from dynamically named form fields, and are captured using a cfloop:
<cfloop list="#form.fieldnames#" index="item">
</cfloop>
What I have are form fields dynamically named, and a value added, as such:
<input type="hidden" name="ticketid_#some_number#" value="#some_quantity#">
For brevity, lets say the form field name is ticketid_6, and the value is 4. This could be a different name and value (for instance, ticketid_3 with a value of 1), or there might be several form fields of similar construct with different names and/or values.
So, on the insert page, I need to insert ticketid_6 4 times (creating 4 separate rows) into my table. So, a row in the database for each dynamically named form field, times the value of each.
I hope that explains it better.
Leigh,
I am still open to your suggestion on the previous post, but I fear I might not have explained my situation clearly enough for you to give your best recommendation. I will re-approach that question after I get this part figured out.
If you need to loop through all your field names and treat each one of those fields as a list you'd need to do two loops to insert each item.
<cfloop list="#form.fieldnames#" index="item"><!--- loop through all the form fields --->
<cfif find('ticketid_',item)><!--- if the form name contains 'ticketid_'. Use findNoCase if you want to ignore case sensitivity --->
<cfloop from="1" to="#form[item]#" index="counter"><!--- loop through the number in form.ticketid_ --->
<cfquery datasource="#dsn#">
INSERT INTO table (fieldname, fieldValue, TicketNum)
VALUES (
<cfqueryparam value="#item#" cfsqltype="cf_sql_varchar">,--fieldName from the form
<cfqueryparam value="#form[item]#" cfsqltype="cf_sql_varchar">--value of the fieldName in the form
<cfqueryparam value="#counter#" cfsqltype="cf_sql_integer">--ticket number being inserted
)
</cfquery>
</cfloop>
</cfif>
</cfloop>
You'll need to do server side validation to verify they haven't entered a non numeric number for the input box, but assuming you've done that this should achieve what you're looking for.
You need to use Evaluate function to get form dynamically input field value
Try this one
<input type="hidden" name="ticketid_#some_number#" value="#some_quantity#">
<cfloop list="#form.fieldnames#" index="item">
<cfoutpuy>Evaluate("ticketid_#item#")</cfoutpuy>
</cfloop>
You need to first bundle your data into an XML structure
<cfsavecontent variable="myFormData">
<cfoutput>
<ul class="xoxo">
<cfloop list="#form.fieldnames#" index="item">
<cfloop list="#form[item]#" index="eachItem">
<li><b>#xmlformat(item)#</b> <var>#xmlformat(eachItem)#</var>
</cfloop>
</cfloop>
</ul>
<cfoutput>
</cfsavecontent>
Then do a single insert
<cfquery>
INSERT INTO table (formData)
VALUES (<cfqueryparam value="#myFormData#" cfsqltype="cf_sql_varchar">)
</cfquery>
When you pull the data, you can
Show it as is, a bulleted list,
Promote to a bunch of rows in a table
Note that the data is inserted as both HTML and XML

How can I use dynamically generated variables from cfloop individually?

I'm not sure my title explains this very well. Frankly, I'm not sure how to put it into words, but here goes:
I am capturing variables from dynamically created form fields on another page, that have been submitted to a page containing the code below. So far, everything works as I want it to. I'm getting the dynamically named form fields. Now I need to add the subtotal dollar amounts together to create a grand total. Unfortunately, I can't figure out how to get the individual totals out of the loop so I can do the math for the final number, due to their dynamic nature.
This part of the code below generates the subtotals, and I need to be able to add all of them together to get a grand total, but I can't figure out how:
#dollarformat(val(getticket[item].ticketprice * form[item]))#
Maybe I need to take a different approach...suggestions/help appreciated.
Here's the full code:
<CFLOOP LIST="#form.fieldnames#" INDEX="item">
<cfoutput>
<cfquery datasource="outertixdb" name="getticket[item]">
select * from tickets
where ticketid = '#item#'
</cfquery>
#getticket[item].ticketname#: #dollarformat(getticket[item].ticketprice)# x #form[item]# = #dollarformat(val(getticket[item].ticketprice * form[item]))#<br/>
</cfoutput>
You would need to set the name attribute of your cfquery using the following format:
<cfquery datasource="outertixdb" name="#getticket[item]#">
To handle the total, you would first need a variable before the cfloop
<cfset total = 0 />
Then, inside the loop, you simply add the price of the ticket to the total
<cfset total = total + getticket[item].ticketprice />
Also, you should be using cfqueryparam in your query. You can read more about it here
Lastly, if you do not need all the data in the tickets table, do not use 'select *..', only pull pack the data that you need.
Not sure I completely understand, but it sounds like you are simply trying to look up a bunch of ticket records, by "id". Then display the individual costs, plus a grand total. If that is all your doing, just give the fields the same name: ticketID. For example:
<input name="ticketID" value="1" ...>
<input name="ticketID" value="22" ...>
<input name="ticketID" value="45" ...>
<input name="ticketID" value="16" ...>
Then the values will be submitted as a list ie 1,22,45,16, which you can feed into your query using an IN clause. That lets you grab all of the data in a single query. (Generally you want to avoid running queries within a loop because performing a separate database query for each id generates a lot of unnecessary overhead and degrades performance).
* Change the cfsqltype as needed
SELECT TicketID, TicketPrice
FROM YourTable
WHERE TicketID IN ( <cfquerparam value="#FORM.ticketID#"
list="true"
cfsqltype="cf_sql_integer">
)
UPDATE:
form[item] is the value of the quantity select from the previous page.
That is a confusing naming convention. I would recommend using a slightly more intuitive name like "quantity". Something more descriptive of the contents. You can still use the ticket id to generate unique names, ie quantity_#ticketID#. For example, using the same ticket id's as above:
<input name="quantity_1" ...>
<input name="quantity_22" ...>
<input name="quantity_45" ...>
<input name="quantity_16" ...>
Once you have the results, there are several ways to generate a grand total. The simplest being to initialize a variable before your loop, then increment it as you iterate. Use the query ticket ID to grab the quantity value from the FORM scope:
<cfset grandTotal = 0>
<cfoutput query="yourQuery">
<!--- extract quantity value --->
<cfset currQuantity = FORM["quantity_"& yourQuery.ticketID ]>
... display price ...
<cfset grandTotal += val(yourQuery.ticketPrice * currQuantity )>
</cfoutput>
GrandTotal <cfoutput>#grandTotal#</cfoutput>
I would recommend throwing out the whole dynamically named query thing.
<cfset total = 0>
<CFLOOP LIST="#form.fieldnames#" INDEX="item">
<cfquery datasource="outertixdb" name="getticket">
select * from tickets
where ticketid = <cfqueryparam cfsqltype="cf_sql_varchar" value="#item#">
</cfquery>
<cfset total += getticket.ticketprice />
<cfoutput query="getTicket">
#ticketname#: #dollarformat(ticketprice)# × #form[item]#
= #dollarformat(val(ticketprice * form[item]))#<br/>
</cfoutput>
</cfloop>
Output your total as needed