简体   繁体   中英

Issue with copying from one MySQL table to another

I'm trying to copy from one table to another table and it works fine, however I also need to insert the current user ID in the new table. I haven't yet figured out how. Normally I would do something like SET user_id = :user_id , but i have never worked with this one.

This is my code:

$q = $conn->prepare("INSERT INTO user_themes(title,code_entry,code_home,code_css,code_category,code_archive)
    SELECT title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");

So my question is: How can I insert user_id (let's say user_id is 1) into the new table as well?

The basis of your query doesn't change. Just add the value to both the columns and `SELECT statement:

INSERT INTO user_themes(user_id, title,code_entry,code_home,code_css,code_category,code_archive)
  SELECT :user_id, title, code_entry, code_home, code_css, code_category, code_archive
    FROM blogy_themes WHERE id = :id

Then when you execute, bind both :id and :user_id .

From what I understand you want to have the id of the user that is doing the action in all of the new records, you can do something like:

$q = $conn->prepare("INSERT INTO user_themes(user_id,title,code_entry,code_home,code_css,code_category,code_archive)
SELECT '" . (int) $userid ."' as user_id, title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");

This is a workaround in order to keep using the query as it is. Second option is more "ORM" approach, you can query all the relevant records from the user_themes table, iterate on the result set, clone each row and save it with new user_id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM