Appending data using MySQL

First let me say this blog post is ripped off directly (word for word) form Coding Tricks.

...... Some times we need to append data into a mysql field. So here is solution. Also the query below checks if the value is NULL then if first enters the empty data to the table field.

UPDATE employee SET notes=CONCAT(COALESCE(notes, ''), 'NewDataHere') where employeeID=13;

In the above query concat('','') is to append the new data to the existing data of the field notes. Other function COALESCE(",") checks for NULL, if the field have NULL value then it will enter an empty '' value to field. Other wise in case of NULL value concat() function will end up with a MySQL error.

...... Now that is a great little trick for adding notes to a record w/o having to first GET the record contents. I love it!

CFWheels? Ruby? Huh?

So I was watching the recording of Ray Camden's "Art of Ajax" and saw a little link in the comments section to Neil Middleton's post on learning a new 'tool'. And it struck me - this is where I am failing.

Yes Michael I saw your comment and I often feel the same way :) Anyway - There in lies my trouble - how do I commit to learning a new tool when I can't even keep up with what I have? Client commitments, Deacon training, Studying up on the responsibilities of being a fiscal agent (I was asked to be the VP of a local fiscal agent organization), beta testing the new Cartweaver Customer contact module, writing an overview on PCI Compliance, keep to my new water aerobics regimen, stay in The Word regularly and be a Godly husband and father. And oh yeah - pay the bills! There is a lot.

So what did I just do? I put a plate full of excuses on my table. Well enough is enough. Neil prompted a '24 hour challenge' to learn a new tool. I accept.

Starting tomorrow (way too much time wasted today already you see) I will commit to 1 hour on Monday, Wednesday and Friday of each week to dig into jQuery a whole lot more than I have. I am really quite the novice. I purchased a [whimpering] few months ago [/whimpering], Jack Born's How to create AJAX Web Applications and I have watched the majority of it and honestly went 'ick!' But that was not for the content but mostly the presentation. I found it to be a little parochial. (Sorry Jack) The content had some really good ideas and the code was well done. But in the end - it was geared for a novice programmer - not an existing programmer who wanted a new tool.

HOWEVER - I am going to go through the entire thing with new eyes and bigger ears. So my commitment to whoever is out there and bothers to read this - I will post each time I learn something during my 24 hour challenge and let you know what I found - no matter how small.

The first thing I should do is find out why this crazy blog will not allow comments. I have tried - really I have. So if anyone recognizes this error in Ray's blog and has been able to resolve it themselves.... Element USECFP is undefined in APPLICATION

please let me know. I have replaced the MySQL driver with the new v5 driver already - so that's a no go. And with the help of a friend I have even taken his default copy of the blog and installed it on my server and it ran w/o a hitch. I am stumped and honestly - frustrated.

God Bless and make it a great day. Chris

Authorize.net Signups

As an authorized reseller I was always ashamed that my clients could not sign up online. Well all that has changed. Do you want an authorize.net account? If so then my rates are the same as every other reseller out there - it is just a matter of support.

Sign up under my account and I will be the one trying to help you along. Sign up with someone else and they will be the ones helping you out. The rates and fees from authorize and the merchant account company will all be the same.

So here it is:

https://ems.authorize.net/oap/home.aspx?SalesRepID=39&ResellerID=8167

Yes you read it right https://ems.authorize.net/oap/home.aspx?SalesRepID=39&ResellerID=8167

Just click it go ahead :)

firing a javascript event on cfcalendar Part 2

It would seem that the yanking of the date and sending along via javascript is not so simple after all. For example - reading the docs (and getting helpful tips form others commenting on Ray's blog ) show me that cfcalendar sets months based on 0-11 and NOT 1-12 - not that's silly - in my humble opinion. No one else computes months that way in their head - why should a computer? There must have been some higher level thinking involved there. Or maybe the guys in the corner of the programming dungeon were concerned for job security so they made something quirky that they would have to support or allow the other big wigs to write more books about :)

Ok - kidding aside - why did they do that? It seems kinda ludicrous. So you know? Let me know then.

Back on to the point there is something else awry. I have a very simple cf page that reads like this...

<cfset request.thispage= cgi.PATH_INFO>
<cfdump var="#server#">
<!--- Set date to work with --->
<cfif isDefined('URL.date')>
    <cfset submitText = "Update Activities">
    <cfset FORM.activityDate = #dateformat(URL.date,'mm/dd/yyyy')#>
<cfelse>
    <cfset submitText = "Submit Activities">
    <cfparam name="FORM.activityDate" default="#dateformat(now(),'mm/dd/yyyy')#">
</cfif>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script LANGUAGE="JavaScript" TYPE="text/javascript">
<cfoutput>
function loadit(y,m,d) {
    var datefield = m+'/'+d+'/'+y;
        alert(m+'/'+d+'/'+y);
window.location.href='#request.ThisPage#?date='+escape(datefield);
}</cfoutput>
</script>
</head>
<cfform>
<cfcalendar name="cal" selecteddate="#FORM.activityDate#" onChange="if(cal.selectedDate) getURL('javascript:loadit(\''+cal.selectedDate.getFullYear()+'\',\''+cal.selectedDate.getMonth()+'\',\''+cal.selectedDate.getDate()+'\')')">
</cfform>
</body>
</html>

Cut and paste this into your huh.cfm document like I did. Then load the page. Does the calendar have today's date loaded ? Good. Now click on a day of the month and carefully read the alert. If yours works - cool - let me host on your server :) If you think it worked but your alert told you that you selected a day in the month PRIOR to the month you are in - then you have the spartamouse bug.

AARRGGHHH - I hate wasting time on trivialities - it stinks and frustrates me.

Comparing a date in MySQL to itself plus some days

Not a very creative title I know but it says what it is...

Last night I was trying to figure out how to search a table for any records where the end date was greater than today OR the end date plus n days was greater than today. My troubles came in that the number of extra days was stored in the record with the end date - it was not a static number...

So I tried a few different things - one of them being:

SELECT contest_ID, DATE_ADD(contest_endDate, INTERVAL contest_extraDays DAY) as enddate
from tbl_contests
WHERE contest_archive = 0
AND contest_StartDate <= CURDATE()
AND enddate >
= CURDATE()

But then I got this really annoying message saying that enddate was not a valid column name.

The solution was a simple one and only one word: HAVING

If you read the MySQL docs on group by and having (sorry the link was so hard to find I can't remember where at the moment) Well anyway - the docs say specifically that you should not use HAVING where you can use AND. This doesn't help - I tried AND.

But a little further reading lead me to confirm that HAVING was the way to go - so I tried. Low and behold it works really really well.

Here is the edited SQL (note - only one word changed )

SELECT contest_ID, DATE_ADD(contest_endDate, INTERVAL contest_extraDays DAY) as enddate
from tbl_contests
WHERE contest_archive = 0
AND contest_StartDate <= CURDATE()
Having enddate >
= CURDATE()

The other part in this was that I learned this morning that I don't always have to use #createodbcdate(now())# in my Mysql Statements - however I amm limited to only using this query on a MySQL db - so maybe I will change it anyway :)

Enjoy, Chris

firing a javascript event on cfcalendar

Thanks to Ray Camden for another interesting post with the solution I needed.

Finally a problem that only took 20 minutes to resolve - I love it. I needed to use cfcalendar to place a calendar on the page with the selected date being based on the form.date field. That was the easy part.

Looking into cfcalendar on livedocs you will see that the onchange event only fires action script. How annoying.

So what then is the answer? Thank you Ray for two little posts that solve it all for me.

It would seem that getURL is an actionscript function that will run any url string - including javascript. So in order to use the calendar the way I wanted I had to do the following...

Javascript code for hte head:

<script LANGUAGE="JavaScript" TYPE="text/javascript">
<cfoutput>
function loadit(y,m,d) {
    var datefield = m+'/'+d+'/'+y;
window.location.href='#request.ThisPage#?date='+escape(datefield);
}</cfoutput>
</script>
cfcalendar tag goes a little something like this :)
<cfform>
<cfcalendar name="cal"selecteddate="#FORM.activityDate#" onChange="if(cal.selectedDate) getURL('javascript:loadit(\''+cal.selectedDate.getFullYear()+'\',\''+cal.selectedDate.getMonth()+'\',\''+cal.selectedDate.getDate()+'\')')">
</cfform>

Thanks again Ray

I learned something new about Navicat today

I am inserting data into a table called users. It contains some basic fields - id,username,email,password,etc. The table is in a MySQL 5 DB and the only key field in the table is the ID field.

So when I insert a record with a duplicate EMAIL I get the following error:

Duplicate entry 'myemail@domain.com' for key 2

Now why would it yell at me for duplicating the email address when it doesn't know I don't want dupes? Now If I dump a SQL file of the table it starts out like this...

CREATE TABLE `tbl_users` (
`user_ID` int(11) NOT NULL auto_increment,
`user_FirstName` varchar(50) default NULL,
`user_LastName` varchar(50) default NULL,
`user_Email` varchar(50) default NULL,
Looking further down I see this:
PRIMARY KEY (`user_ID`),
UNIQUE KEY `user_Email` (`user_Email`),
KEY `user_ID` (`user_ID`)

Now where did that come from?

I don't remember putting it there? I don't even know how. Then it strikes me - I copied this user table from another database that was probably created by someone else ages ago and I simply manipulated it for my own needs.

So how do I check for unique keys like that in Navicat? Well look around I say and what you find might might surprise you - if you're not all that familiar to Navicat that is. I use it simply to create some tables, massage data once and a while, export data, copy application databases from one app to a new one. But once and a while I do something different - or try to - and find neat little tricks in Navicat.

So I looked around and what do you know - a tab called indexes. And there it was the email index type was - of all things - UNIQUE. Hot diggity!

Did you know that tab was there? Do you know where it is? It is in the table design view. Go ahead I dare you - select a table and click design. Then stop looking at all the fields in your table and look at the tabs just above.

Did you know you can set foreign keys right in Navicat - no SQL needed :) Did you know you can change the table type or set up triggers? I didn't - but now I do. And bet you a Moxie that by this time tomorrow - I will have forgotten all about it. That's why I write this blog anyway - so I can go look up what I forgot.

Good night

Retrieving last inserted record from MySQL

ok its easy as can be....

Create an insert query ..

<cfquery name="qInsert" datasource="#dsn#">
INSERT INTO tbl_foo (field1,field2) values (
<cfqueryparam cfsqltype="cf_sql_varchar" value="#value1#">
,<cfqueryparam cfsqltype="cf_sql_varchar" value="#value2#">)
</cfquery>

then immediately following that create the next query..

<cfquery name="q" datasource="#dsn#">
    SELECT LAST_INSERT_ID() as ID;
</cfquery>

What I haven't tried is running both SQL statements in one cfquery - maybe later tonight :)

<cfquery name="qInsert" datasource="#dsn#">
INSERT INTO tbl_foo (field1,field2) values (
<cfqueryparam cfsqltype="cf_sql_varchar" value="#value1#">
,<cfqueryparam cfsqltype="cf_sql_varchar" value="#value2#">);
SELECT LAST_INSERT_ID() as ID;
</cfquery>

I'll let you know.

Looks Like a NO GO. I tried - I flopped on my face :(

By the way - I forgot to mention - this select statement only works when you have a self incrementing key field in your table. If you are setting the key field yourself - well you already know the key so you don't need that statement :)

Thank you to Michael Evangelista for pointing me to the [humbled]Jedi Master[/humbled] Take a look see over here and be amazed... http://www.coldfusionjedi.com/index.cfm/2007/6/15/ColdFusion-8-Getting-the-autonumber-insert-ID

Passing a file to a cfc via another cfc

Ok so the scenario is this: I have a form containing five or six items..

<cfform name="addForm" id="addForm" action="#request.ThisPageQS#" method="post" enctype="multipart/form-data" >
<cfinput name="category" value="foo" type="hidden">
<cfinput name="my_ID" value="#url.myID#" type="hidden">
<cfinput type="text" value="#form.text_Title#" name="text_Title">
...various other fields...
<cfinput type="file" name="text_Image" id="text_Image">
</cfform>

Now to process this form I have a simple cfc that

  1. tests for new or update based on the value of form.my_id
  2. Uploads the file
  3. Adds or updates the database record as needed

The cfc looks like this...

<cffunction name="updateText"> <!--no it's not undocumented like this but I am trying to save room :) -->
<cfargument name="category">
<cfargument name="my_ID" default="0">
<cfargument name="text_Title">
<cfargument name="text_Image">

<cfif len(arguments.text_Image) NEQ 0>
<cfset setImage(category,"text_Image")>
</cfif>

<cfswitch expression="#arguments.text_ID#">
<cfcase value="0"> <!--- Add a record ---></cfcase>
<cfdefaultcase><!--- Update a record ---></cfdefaultcase><cfswitch>

Now in the same cfc is the function setImage() and it looks like this:

<cffunction name="setImage" >
<cfargument name="category" >
<cfargument name="file" default="" hint="This MUST BE the NAME of the form field name - not that value of the form field">

<cfif not directoryExists("#expandPath('../')#img/#category#")>
<cfdirectory action="create" directory="#expandPath('../')#img/#category#">
</cfif>
<!--- Insert uploaded file--->
<cflock name="crDir" timeout="30" type="exclusive">
<cffile action="upload" filefield="#arguments.file#" destination="#expandPath('../')#img\#category#\" nameconflict="overwrite" accept="image/*">
</cflock>
<cfreturn cffile.clientFile>

</cffunction>

Notice the hint for the setImage function... "This MUST BE the NAME of the form field name - not that value of the form field"

So what's the purpose of this post anyway? Glad you asked - it is simply to show that cffile requires the name of the file field you are using and not the value of the file field. cffile will find the value on it's own.

If you were for example to call the function using

The form field C:\ColdFusion8\runtime\servers\coldfusion\SERVER-INF\temp\wwwroot-tmp\neotmp4695.tmp did not contain a file.

Simply because it tries to get the file itself - so if you give it the file contents and say look for the file contents it is kind of like pouring water over someone's head and asking them to take the water out instead of handing them the bucket full of water and asking the same thing.

I know bad analogy - but it was all I could come up with for now. You have a better one? send it my way :)

site mappings

Just a simple concept but amazingly handy... this.mappings

In my application.cfc I have a line in the header script section that reads: this.mappings["/gadget"] = getDirectoryFromPath(getCurrentTemplatePath());

Don't ask my why I put it there - I don't know except that it was included n the sample application.cfc I was learning from months back. I can't remember if it was in one of Ray's Application.cfc samples or from one of Ben Nadel's version But anyway - it's there.

[More]

More Entries

BlogCFC was created by Raymond Camden. This blog is running version 5.9.3.000. Contact Blog Owner