edynas Posted April 14, 2007 Share Posted April 14, 2007 I got a maybe stupid question I want to insert data into a table. In the table are 3 rows of which one is an id with autoupdate. In the loop where I do the insert I also want to do an other insert but need the value of the id. I have seen several solutions to this but want to make sure I get it right. One way is to count the table and the number of rows should be the number of the id. But I am afraid to use this methode as over time there maybe some deletions of rows and that will effect the number. An other is to call the id value before entering the loop set a variable with the name y (or whatever) with that value and use the ++ at the end of the inner loop to up the id and I saw some bits and pieces of a function that calls the id of the last insert. I need some advice..what is the best way to do this Quote Link to comment https://forums.phpfreaks.com/topic/47023-get-id-after-autoupdate/ Share on other sites More sharing options...
MadTechie Posted April 14, 2007 Share Posted April 14, 2007 use mysql_insert_id () int mysql_insert_id ( [resource $link_identifier] ) Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. Quote Link to comment https://forums.phpfreaks.com/topic/47023-get-id-after-autoupdate/#findComment-229326 Share on other sites More sharing options...
edynas Posted April 14, 2007 Author Share Posted April 14, 2007 Great so the code for it would be something like this if the columns are id, name, description while ($A = mysql_fetch_array($opdracht)) { $sql = mysql_query("INSERT INTO cat (`id`, `cat_name`, `cat_desc`) VALUES ('', $cat_name, $cat_desc)" ); $cat_id = mysql_insert_id ( [id] ); $sql = mysql_query("INSERT INTO product2cat (`id`, `cat_id`, `name`, 'descr' ) VALUES ('', $cat_id, $product_name, $desc)" ); } Quote Link to comment https://forums.phpfreaks.com/topic/47023-get-id-after-autoupdate/#findComment-229335 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.