Jump to content

Copy a row within same table


Go to solution Solved by Barand,

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/324757-copy-a-row-within-same-table/
Share on other sites

  • Solution

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.

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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.