phppup Posted October 11 Share Posted October 11 I'm trying to copy a row so that I can later update within a given table. I'm not sure if there's a syntax error or rule error, or a missing piece but this code is not doing the job. $sql = "INSERT INTO $table (id, company_name) SELECT id, company_name FROM $table WHERE id = 26"; The table has auto increment ID, but the many alterations that I've made have failed. Guidance or solution, please. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/324757-copy-a-row-within-same-table/ Share on other sites More sharing options...
Solution Barand Posted October 11 Solution Share Posted October 11 the id is unique, so you can't insert a second id of 26. Omit the id column from the query then the rest of the columns can be inserted (unless any are defined UNIQUE in which case you need to omit those too) $sql = "INSERT INTO $table (company_name) SELECT company_name FROM $table WHERE id = 26"; You can call a lastInsertId() function to get the id of the new record. Quote Link to comment https://forums.phpfreaks.com/topic/324757-copy-a-row-within-same-table/#findComment-1637377 Share on other sites More sharing options...
phppup Posted October 11 Author Share Posted October 11 Ok, it seems to be working now (so I can build out on it). To be truthful, I had tried that (you taught me well) but your confirmation lead me to a different dumb mistake, as I was toying with this piece of code at the bottom of a PHP page and neglected to remove the line containing: mysqli_close($con) Therefore, there was no connection. Hence, failure. What sort of PHP could I use to alert me and prevent this type of issue. Note: I check the connection at the top of the page using if($con === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } but it doesn't trigger (with the terminated connection in place) because $con is still valid. Thanks for the help. Quote Link to comment https://forums.phpfreaks.com/topic/324757-copy-a-row-within-same-table/#findComment-1637387 Share on other sites More sharing options...
phppup Posted October 11 Author Share Posted October 11 It seems that the auto increment for the ID prohibits use of an asterisk (to SELECT * and use everything EXCEPTÂ the ID in the insert). Is there a lazy workaround (that's worthwhile)? Quote Link to comment https://forums.phpfreaks.com/topic/324757-copy-a-row-within-same-table/#findComment-1637390 Share on other sites More sharing options...
Barand Posted October 12 Share Posted October 12 Yes, don't use select * ... Also, there is no need to close a connection at the end of a page - php does this automatically for you. Quote Link to comment https://forums.phpfreaks.com/topic/324757-copy-a-row-within-same-table/#findComment-1637429 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.