Hi everybody!
Could you teach me how to get back the “primary key”: (“id”), from an “insert query”?

*

<cffunction name="insertData" access="public">
  <cfargument name="formData" type="struct" required="yes">
  
  <cfquery name="qInsert" datasource="mydata">
                    INSERT INTO mytable
                        (email, firstname, name)
                    VALUES
                        ('#formData.email#', '#formData.firstname#', '#formData.name#')
           </cfquery>
</cffunction>

*
How could I get back the primary key:”id” and send it to another page? (MySQL)
Thanks a lot!

Recommended Answers

All 3 Replies

Use SCOPE_IDENTITY(). It will return the id of the record just created, provided the field is set as the identity column.

<cffunction name="insertData" access="public">
  <cfargument name="formData" type="struct" required="yes">
  
  <cfquery name="qInsert" datasource="mydata">
       INSERT INTO mytable
          (email, firstname, name)
       VALUES
          ('#formData.email#', '#formData.firstname#', '#formData.name#')

       SELECT id = SCOPE_IDENTITY()
   </cfquery>

   <cfreturn qInsert.id />

</cffunction>

Thank you, cmhampton !
How about cfquery: "result" ?What you prefer?
H.

Use SCOPE_IDENTITY(). It will return the id of the record just created, provided the field is set as the identity column.

<cffunction name="insertData" access="public">
  <cfargument name="formData" type="struct" required="yes">
  
  <cfquery name="qInsert" datasource="mydata">
       INSERT INTO mytable
          (email, firstname, name)
       VALUES
          ('#formData.email#', '#formData.firstname#', '#formData.name#')

       SELECT id = SCOPE_IDENTITY()
   </cfquery>

   <cfreturn qInsert.id />

</cffunction>

Thank you, cmhampton !
How about cfquery: "result" ?What you prefer?
H.

I'm not sure I understand your question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.