I’m running into trouble when trying to get the auto-increment ID inside a foreach loop:
<xsl:for-each select="(1,2)">
<xsl:variable name="insertQuery">INSERT users SET name="User{.}", created=NOW()</xsl:variable>
<saxon:do action="sql:execute($dbConnection, $insertQuery)"/>
<xsl:variable name="newId" select="sql:prepared-query($dbConnection, 'SELECT LAST_INSERT_ID() AS new_id')()?new_id"/>
<xsl:variable name="updateQuery">UPDATE orders SET user_id={$newId} WHERE order_id={position()}</xsl:variable>
<saxon:do action="sql:execute($dbConnection, $updateQuery)"/>
<saxon:do action="$dbConnection?commit()"/>
</xsl:for-each>
During the first iteration everything works fine. The record gets inserted, I retrieve the correct LAST_INSERT_ID(), and the orders table gets updated properly. But in the second iteration, even though the new record is inserted successfully, the LAST_INSERT_ID() query returns the ID from the first iteration instead of the current one.
I think maybe the second prepared query is running out of order or getting cached since the query string is the same. When I add unique text like position() to make each query different, it works correctly. What’s the best approach to make sure the ID query always runs after the insert statement?