0

I'm using coldfusion to insert the contents of a struct (key-value pairs) into a database table. This is my code:

<cfloop collection="#results#" item="ID" >
    <cfquery name="insertStuff" datasource="myDataSource">
        INSERT INTO web..Stuff (ID, Name)
        VALUES (#ID#, #results[ID]#)
    </cfquery>
</cfloop>

This seems simple enough... but I'm getting the following error:

Incorrect syntax near 'VA'. 

Any ideas?

froadie
  • 79,995
  • 75
  • 166
  • 235

2 Answers2

10

You really ought to think about parameterising your data too.

<cfloop collection="#results#" item="ID" >
    <cfquery name="insertStuff" datasource="myDataSource">
        INSERT INTO web..Stuff (ID, Name)
        VALUES (
            <cfqueryparam cfsqltype="cf_sql_varchar" value="#ID#">, 
            <cfqueryparam cfsqltype="cf_sql_varchar" value="#results[ID]#">)
    </cfquery>
</cfloop>
Steve Martin
  • 1,632
  • 10
  • 19
  • To Steve's point, using the cfqueryparam will do a lot for you. It would have quoted the string 'VA' for you while protecting you from a whole bunch of bad stuff. Even in an Intranet app, you want to do this. – Aaron Greenlee Dec 20 '10 at 11:45
  • good point... thanks. I'll definitely try this. I'm getting back into cf after a long break from it... so there're a lot of things I've forgotten about :) – froadie Dec 20 '10 at 12:09
2

I think I may have solved it... forgot the quotes, and they're both varchar fields :-/

<cfloop collection="#results#" item="ID" >
    <cfquery name="insertStuff" datasource="myDataSource">
        INSERT INTO web..Stuff (ID, Name)
        VALUES ('#ID#', '#results[ID]#')
    </cfquery>
</cfloop>
froadie
  • 79,995
  • 75
  • 166
  • 235