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.
Related
Writing in Linux/Lucee and Coldfusion/Mysql. I have several databases in my system, with quite a few tables overlapping. I have a program which would add a field to a given table, say Activity, in each database. Of course I don't want to alter a non-existent table, so I am checking to make sure the table is there.
The simplest way would be to go to the database and use "show tables like 'Activity'". To do that in ColdFusion I used the datasource that belongs to that database. However, when I tried that, I got zero tables even when the table is present.
<cfquery name = 'tbl' datasource = '#thedatasource#'>
show tables like 'Activity'
</cfquery>
The record count for this query is zero. Then I tried using the information schema and got better results with this test program:
<cfquery name = 'dblist' datasource = 'Moxart'>
select MoxcoId from Moxco
</cfquery>
<cfloop query = 'dblist'>
<cfoutput>
<cfquery name = 'tbl' datasource = 'Moxart'>
select table_schema,table_name from information_schema.tables
where table_schema = '#MoxcoId#' AND table_name = 'Activity'
</cfquery>
<cfdump var = '#tbl#'>
</cfoutput>
</cfloop>
This gave exactly the right answer. However, when I put the same code into the real program, it keeps returning zero records. The real program is rather long, however most of the beginning consists of picking up info from the previous form . From the line
<cfquery name = 'dblist' datasource = 'Moxart'>
the only difference is the addition of this section because #MoxcoId# is not always the schema name. The variable #mmox# is in this case blank, so doesn't add anything.
<cfif #MoxcoId# EQ 'Moxart'>
<cfset pref = '#mmox#Moxware'>
<cfelse>
<cfset pref = '#mmox##MoxcoId#'>
</cfif>
When I do a dump on the query 'tbl' it shows that zero records were retrieved, even though the code appears to be exactly correct.
I am baffled. There must be something wrong in my code, but I just can't see it. If anyone can suggest something I would appreciate it.
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.
My purpose is since the time I login my page, I want my web to show how many updated data in the database. My code is like this
$current = $_SESSION['date'];
$query2 = "SELECT * FROM gmaptracker1 WHERE datetime >= '$current'";
When I echo the $current, it showed 27/09/14 : 06:53:24, so the $current is correct, however, when I request the number of database where date>='$current', I get zero, although I have inserted to the database the data with datetime 28/09/14 : 06:53:24 and 29/09/14 : 06:53:24.
Can anyone help me to get out of this, please?
Few things,
It seems like your code is vulnerable to SQL Injection. Just because you retrieve the content of the date from a session, it doesn't mean that it's safe.
Also, why do you need it to be in a session variable? If you always want to retrieve dates bigger than NOW() you can just write your query this way:
SELECT * FROM gmaptracker1 WHERE datetime >= NOW()
The part that caught my attention was the format you're storing the dates.
You said that when you echo'ed $_SESSION['date'] the value was: 27/09/14 : 06:53:24
Now, that does not look like the date format at all. Is your column actually a datetime or timestampcolumn?
If it's a VARCHAR or any other type other than datetime or timestamp, then there's no way for MySQL to know that you're trying to retrieve dates that occur in the future.
If you already have data stored, then it isn't going to be as easy as changing the data type because you already have data, and your data is in the wrong format. The format that MySQL stores datetime information is as follows:
YYYY-MM-DD HH:MM:SS
Based on the comments you left, you don't need the time > NOW(), you need the time when you log in. Now it makes sense why you're storing that time in a variable.
The problem is the format you're storing it.
Since you're using PHP, then you have to store the time this way:
$time = new DateTime();
$_SESSION['date'] = $time->format("Y-m-d H:i:s");
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'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