chick3n Posted December 5, 2007 Share Posted December 5, 2007 After i perform an INSERT INTO to 1 table, can i set up the database to automatically make another insert into another table using the last insert id? I do this already with PHP but im wondering if you can set up MySQL to do it automatically. Would i use 'triggers'? Example: 2 tables, table1 & table2 -> INSERT INTO table1 (junk, text) VALUES ('sss', 'sss'); After that query is performed i want the database to automatically create a new row in table2 with the last insert id and the tables default values. Quote Link to comment Share on other sites More sharing options...
teng84 Posted December 6, 2007 Share Posted December 6, 2007 php function --- mysql_insert_id() gets the last insert id from the current connection Quote Link to comment Share on other sites More sharing options...
fenway Posted December 6, 2007 Share Posted December 6, 2007 Depends what you mean by "automatically". Quote Link to comment Share on other sites More sharing options...
chick3n Posted December 7, 2007 Author Share Posted December 7, 2007 php function --- mysql_insert_id() gets the last insert id from the current connection Yes i know that, i just wanted to know if their was an automated way of doing it instead of coding it like that. No matter what if their is an INSERT performed on this table another INSERT will need to be performed on another table always. But if the second insert fails the whole process should fail and the first insert should be deleted. I guess this is where i would use transactions? Quote Link to comment Share on other sites More sharing options...
fenway Posted December 7, 2007 Share Posted December 7, 2007 Yup, transactions would apply here -- I don't think you can rollback a trigger... unless you trigger an SP... but I don't do things like that, so I don't know. Quote Link to comment Share on other sites More sharing options...
chick3n Posted December 7, 2007 Author Share Posted December 7, 2007 Yup, transactions would apply here -- I don't think you can rollback a trigger... unless you trigger an SP... but I don't do things like that, so I don't know. Fenway ive done the implementation part, and run the scripts and my code still works like it was supposed to however im curious to test a fail case. Is their anyway to force a fail in this scenario. Or should i just use the assumption in the testing code that "hey this insert just failed (even though it really didnt) and call rollback" and see what happens? Quote Link to comment Share on other sites More sharing options...
fenway Posted December 7, 2007 Share Posted December 7, 2007 How do you define failed? No record inserted? If so, just cause a key collision. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.