简体   繁体   中英

Save primary ID in another column in MySQL Table

i have this MySQL Table:

    CREATE TABLE web_media_com (
    web_media_id INT AUTO_INCREMENT PRIMARY KEY,
    web_media_position INT(12),
    web_media_headline VARCHAR(76),
    web_media_description VARCHAR(680)
    );

I would like to add the primary id to the "web_media_position" in one INSERT INTO query. So when "web_media_id" gets the id 234 then "web_media_position" should get the same 234 number.

Right now i have this:

    $mysql_query = "INSERT INTO `web_media_com` (web_media_position, web_media_headline, web_media_description) VALUES
    (LAST_INSERT_ID(), '".$web_media_headline."', '".$web_media_description."')";

But this does not work. Can someone please tell me how i can do This? thanks!!!

Use a transaction to prevent conflicts between concurrent inserts.

In straight (non PHP) sql it would look something like:

START TRANSACTION;
   INSERT INTO web_media_com(columns)....
   SET @entry_id = LAST_INSERT_ID();
   UPDATE web_media_com set web_media_position = @entry_id 
      where web_media_id = @entry_id;
COMMIT;

(NOTE: I didn't try this is in a fiddle.. YMMV...)

Best Solution For You

$mysql_query =
 "INSERT INTO web_media_com 
    (web_media_position, web_media_headline, web_media_description) 
    select MAX('id')+1,'".$web_media_headline."','".$web_media_description."' 
      from web_media_com";

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