Kevin
Kevin

Reputation: 13226

Insert a Coldfusion struct into a database

If I wanted to save a contact form submission to the database, how can I insert the form scope in as the submission? It's been some time since I used Coldfusion.

The contact forms vary depending on what part of the site it was submitted from, so it needs to scale and handle a form with 5 fields or one with 10 fields. I just want to store the data in a blob table.

Upvotes: 4

Views: 2757

Answers (5)

Jack Poe
Jack Poe

Reputation: 1

I do this one all the time. In fact, for forensics, I have a script that records every form submission on our sites at work.

You can use the serializeJSON() function against the FORM scope like so...

<cfset theForm = serializeJSON(form)>

Then just insert it into your database.

If you want to make it secure - if the form contains PII, for instance - you could also encrypt the JSON string with the encrypt() function. Just generate a secret key in the algorithm of your choice and store it as an application variable. That way you can encrypt and decrypt the contents as needed.

Upvotes: 0

David Collie
David Collie

Reputation: 612

Cfwddx is also an alternative.

Upvotes: 2

Henry
Henry

Reputation: 32885

If you can't normalize the form fields into proper table(s), you can try storing them:

  • in XML (SQL Server supports XML pretty well), or
  • in JSON (in a plain varchar field), or
  • ObjectLoad() & ObjectSave() (CF9 only) to store as blob.

IIRC there are ways to get object load/save functionality in pre-CF9 by tapping into Java. http://www.riaforge.org/ or http://cflib.org/ might have it.

Upvotes: 0

Joe D
Joe D

Reputation: 3708

I don't know that there is a way to store a native structure into a database, but have you thought about using JSON to represent your object as key-pair values and then parsing it into a native structure after retrieving it from the database?

There are tags/functions out there that will help you with the encoding and decoding into JSON:

Upvotes: 0

zarko.susnjar
zarko.susnjar

Reputation: 2053

Most space efficient way and least complicated to turn back into original shape is using serializeJSON. After that, you can use something like key:value|key:value, or XML representation of your struct.

Upvotes: 8

Related Questions