I'm moving from an MS Access backend to mySQL. This used to work but now doesn't and I can't figure the problem.
<cfargument required="false" name="expiry" type="any" default="" />
<cfquery datasource='#arguments.dsn#'>
INSERT INTO users(expiry)
VALUES (<cfqueryparam value="#arguments.expiry#" cfsqltype="CF_SQL_TIMESTAMP"/>)
</cfquery>
The database field is set to datetime and default NULL
The argument is populated from a form field which is either empty, or a javascript validated date. It chokes on empty formfield.
Before you mess with the DSN settings, I would also try changing your <cfqueryparam> to the following:
<cfqueryparam value="#arguments.expiry#" cfsqltype="CF_SQL_TIMESTAMP" null="#len(arguments.expiry) eq 0#" />
This will pass a true null in the event that the argument value is an empty string.
CF's implementation of the JDBC driver for MySQL doesn't handle NULL dates very well.
You need to add a config flag to your DSN connection string settings (under advanced) in the CF admin
&zeroDateTimeBehavior=convertToNull
Should set you right.
Rob
Related
I'm a beginner so I Want to know how you can check if a name already exist in the database and give an alert or a message saying the name already exist in the database
but i don't want to use jquery or js just cf and the queries.
<cfif isDefined("Button")>
<cfquery name='Insert' datasource='mysql'>
INSERT INTO tbl_products_manager
(Name)
VALUES ('#name#')
</cfquery>
<cfinclude template="pr.cfm">
</cfif>
I want to know what i should write in the next cfquery or to add the message
You can do:
<cfquery name='Insert' datasource='mysql' result='local.stResult'>
INSERT INTO tbl_products_manager
(Name)
VALUES (<cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#name#" />)
WHERE NOT EXISTS (SELECT 1 FROM tbl_products_manager WHERE Name = <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#name#" />)
</cfquery>
Then you can dump local.stResult and figure out the result value that has the modified record count. (Can't remember offhand.) If the value is 0, you know it wasn't inserted.
As you indicate you are new to Coldfusion, please, please look up <cfqueryparam> and use it in every...single...query, every time.
The above is but one solution. You can also do a separate query first. Or you can have an identity (or MySQL equivalent) on the table and also get that in the stResult struct. There are a myriad of ways. Strenghten your sql-fu, and your CFML query/proc usage will get stronger, too!
I'm working on a submission form for events that once completed, goes to a processing page and updates a database.
I have fourteen fields, several are required one of which is the date and time of the event.
During the processing of the form I join the two form entries, date and time before attempting the insert into the database but an error occurs.
Data truncation: Incorrect datetime value
Here is the code elements that are failing:
<cfset insdate = form["date"] & form["time"]>
<cfset new_date = #CREATEODBCDATETIME(insdate)#>
<cfif len(trim("#institle#"))>
<cfquery name="modify">
INSERT INTO table
SET
title = <cfqueryparam
cfsqltype="CF_SQL_LONGVARCHAR"
value="#institle#">,
dateTime = <cfqueryparam
cfsqltype="CF_SQL_LONGVARCHAR"
value="#new_date#">,
location = <cfqueryparam
cfsqltype="CF_SQL_LONGVARCHAR"
value="#inslocation#">,
category = <cfqueryparam
cfsqltype="CF_SQL_SMALLINT"
value="#inscategory#">,
type = <cfqueryparam
cfsqltype="CF_SQL_TINYINT"
value="#instype#">
</cfquery>
</cfif>
I've trimmed the code above to make it shorter and easier to read. If anyone has any ideas what I'm doing wrong, that would be great.
I'm running Coldfusion 8, a mySQL database and the database accepts datetime on the field in question, in a yyyy-mm-dd hh:mm:ss format.
Cheers.
ColdFusion can handle string representations of several datetime formats using cfSqlType="CF_SQL_TIMESTAMP", as already suggested. There is no need to create a date(time) object for the query at all. Just make sure that isDate(yourDateTimeString) returns true for the string (because that's what CF_SQL_TIMESTAMP will assume) and be aware of differences in the locale. (ddmmyyyy and mmddyyyy are two obnoxious formats that will be mixed up by ColdFusion, I guarantee it.)
Just cut to the chase here. Alter your code to:
<!--- create a date object --->
<cfset new_date = CREATEODBCDATETIME(insdate)>
<!--- format for the DB --->
<cfset new_date = dateformat (new_date, 'yyyy-mm-dd') & ' ' & timeformat(new_date,'HH:mm:ss')>
See if that inserts for you. most DBs take a string and implicitly convert to dattime internally.
Question: What data type do I use when invoking JSON data from a database using ColdFusion?
Background: My application needs to pull some JSON data from a database and parse the data into an HTML form.
Below is my code so far:
<cftry>
<cfinvoke component="UserData.cfc.data" method="editData" returnvariable="editReturn">
<cfinvokeargument name="formID" value="#URL.dataID#">
</cfinvoke>
<cfset ReBuild = DeserializeJSON(#editReturns#)>
<cfcatch type="Any">
<cfoutput>
<hr>
<h1>Other Error: #cfcatch.Type#</h1>
<ul>
<li><b>Message:</b> #cfcatch.Message#
<li><b>Detail:</b> #cfcatch.Detail#
</ul>
</cfoutput>
<cfset errorCaught = "General Exception">
</cfcatch>
</cftry>
UserData.cfc.data:
<cffunction name="editData" access="public" returntype="any">
<cfargument name="formID" required="yes">
<!--- Select --->
<cfquery name="UserData" datasource="RC">
SELECT Data
FROM USER_Forms
WHERE ID = <cfqueryparam value="#ARGUMENTS.formID#">
</cfquery>
<!-- The information pulled from the database should be a Serialized JSON data. -->
<cfreturn UserData>
</cffunction>
Error Message:
Other Error: Expression
Message: Complex object types cannot be converted to simple values.
Detail: 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 tried to use a complex value as a simple one. For example, you tried to use a query variable in a cfif tag.
When I added the data to the database I used the following process:
<cfset ForDBInsert = SerializeJSON(formCopy)>
<!-- Then I INSERTED ForDBInsert into the database columnn. -->
Try DeserializeJSON(editReturns.data) - notice I took out the # they are not needed when passing arguments this way. Looks like you are trying to deserialize the entire query object rather than the string itself.
I have set up a file that reads an xml file from one database and inserts that data into another. All works well except a strange error on the date format. The date format I need is yyyy-mm-dd. However, the original data is set up as format dd-mm-yyyy.
My code reads and inserts all the data, but when it reads the date field, there is an issue when the day is under 12. It strangely inserts it the other way around.
If a date is 11/10/2014, it pulls it in as 2014/11/10
But, if a date is 13/10/2014, it pulls it in as 2014/10/13 (which is correct and what I need).
If I set the MySQL field type to text or varchar, it inserts the value in the correct order, but of course not in a date format for ColdFusion. So it inserts a date as 11/10/2014, but when I set the same field to type 'date' or even 'date time' format, it inserts it in the correct format '2014-10-11 but with the issue above.
The code I'm currently working with is:
<cfif isDate(arrA[currentField])>
#currentField# = '#LSdateformat(arrA[currentField],"yyyy-mm-dd")#'
<cfelse>
#currentField# = '#arrA[currentField]#'
</cfif>
My second attempt was using the following:
<cfif isDate(arrA[currentField])>
#currentField# = '#ParseDateTime(arrA[currentField],"yyyy-mm-dd")#'
<cfelse>
...
I then receive the following error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '1900-01-01 00:00:00'}' , ScheduleReferenceNumber = 'TS8279631'
,' at line 15
On the third attempt, I used:
<cfloop collection="#arrA#" item="currentField">
<cfif currentField NEQ 'TypeDesc'>
<cfif fieldcount NEQ 0>,</cfif>
<cfif currentField eq 'startDate'>
<cfqueryparam cfsqltype="cf_sql_date" value="#currentField#">
<cfelse>
#currentField# = '#arrA[currentField]#'
</cfif>
<cfset fieldCount=fieldCount+1>
</cfif>
</cfloop>
But I then get the error:
The cause of this output exception was that:
coldfusion.runtime.locale.CFLocaleBase$InvalidDateTimeException:
StartDate is an invalid date or time string..
Having also tried:
<cfset DateLocale = "English (UK)">
<cfset DateString = "11/10/2014">
<cfloop collection="#arrA#" item="currentField">
<cfif currentField NEQ 'TypeDesc'>
<cfif fieldcount NEQ 0>,</cfif>
<cfif currentField eq 'startDate'>
<cfqueryparam value="#LSParseDateTime(dateString, dateLocale)#" cfsqltype="cf_sql_timestamp">
<cfelse>
#currentField# = '#arrA[currentField]#'
</cfif>
<cfset fieldCount=fieldCount+1>
</cfif>
</cfloop>
<cfif checkRecord.recordcount neq 0>
WHERE ScheduleReferenceNumber = '#arrA.ScheduleReferenceNumber#'
</cfif>
</cfquery>
I get the following:
Error Executing Database Query.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''2014-10-11 00:00:00.0' , Currency = '' , Tutor = '' ,
CourseLoc' at line 17
You forgot to specify a Locale. When omitted, the LS date functions use the current page's Locale. Sounds like yours is "English (US)". Per U.S. date conventions, month is always first. So the string "11/10/2014" will always be treated as November 10th, not October 11th.
That said, if you are populating a date/time column, you should use cfqueryparam and pass date objects to the database, rather than date strings, which can be misinterpreted, depending on database settings.
One option is to use LSParseDateTime() with an appropriate Locale. Do not use ParseDateTime(). Like most of the standard date functions, it always uses U.S. date rules, and will produce the same wrong results you are getting now.
<cfset DateLocale = "English (UK)">
<cfset DateString = "11/10/2014">
...
<cfquery ...>
INSERT INTO Table ( SomeColumn )
VALUES (
<cfqueryparam value="#LSParseDateTime(dateString, dateLocale)#"
cfsqltype="cf_sql_timestamp">
)
</cfquery>
Also, for validation, be sure to use the LS version of IsDate. Again with the appropriate Locale.
<cfif LSIsDate( dateString, dateLocale )>
....
</cfif>
NB: Keep in mind CF's date functions are notoriously "generous" about what is considered valid. If the format of your date strings can vary, you may want to implement your own date validation.
Assuming your database datatype is date or something similar, you are using an inappropriate function. LSdateformat() converts a date to a string. The function that converts a string to a date is ParseDateTime().
If your date fields are always arriving with the same format, you can hard code the appropriate mask argument of function ParseDateTime(). If they vary, you'll have to use conditional logic to determine the correct mask.
You should also be cautious about using isDate(). It returns true on some unexpected values such as "apr 31". Combining it with ReFind() and len() would be more thorough.
I've been building a new coldfusion application leveraging object oriented approach and stored procedures. While everything works like a charm, the app is very fast due to SPs and optimized mysql code, I would really appreciate if you would help me clear one thing up :) I have dbcode.cfc which as you probably already guessed stores all queries with stored procedures. That said, generally what's the best approach when it comes to storing global DNS parameters?
1.this can be used for one global DSN
<cfset this.datasource ="myDB">
2.this can also be used for one global DSN
<cffunction name="onApplicationStart" returnType="boolean" output="false">
<cfset application.dsn = "myDB">
<cfset application.username = "userName">
<cfset application.password = "password">
<cfreturn true>
</cffunction>
2.1 everything as above but onRequest
3.in my case I could also create a global variables within the dbcode.cfc
<cfset variables.dsn = "myDB">
<cfset variables.username = "userName">
<cfset variables.password = "password">
4.additionally one could use something like this for setting multiple datasources
<cffunction name="onApplicationStart" returnType="boolean" output="false">
<cfset application.myDSNs = StructNew()>
<cfset application.myDSNs.1 = "myDB1">
<cfset application.myDSNs.2 = "myDB2">
.
.
.
<!---something similar for usernames and passwords--->
</cffunction>
so what's the most efficient way to handle this sort of thing?
Let me see if I can answer each part of your DSN questions.
Setting the datasource as a part the application.cfc constructor is OK
Setting up the DSN in OnApplicationStart() works too, but you need to use:
<cfset application.datasource = "myDB">
2.1 Setting the datasource on every request is pointless, unless you datasource changes with every request. I suspect is does not
You should not touch queries.cfc. That is internal to ColdFusion and has the potential to break everything on your server.
You may want to read on up on the difference between arrays and structs. It looks like what you wanted to do was:
<cfset application.myDSNs = ["MyDB1", "MyDB2]>
They would then be accessable via:
#application.myDSNs[1]#
#application.myDSNs[2]#
I would not do this approach. Databases are typically not arrays of anything. Each server has its own purpose. You DSNs should be reflective of one of more of the following:
The Server
The Database
Purpose