SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Member
    Join Date
    May 2012
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Possible to make foreign key auto update?

    Hi guys,
    The scenario:
    I can submit new article and upload picture for that article.
    So lets say i submitted a new article with an image. Base on the table below, my new article_id will be 2. Then problem is how the foreign key in image table auto update the article_id = 2. So that the image name auto matches the article_id i newly submitted. How do i do that?


    Code:
    articles table:
    article_id content
    1              xxx
    
    image table(stored all the article images):
    id    article_id(foreign key)     name
    1            1                         xyz.jpg

  2. #2
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    You normally don't change id keys values.

    PK/FK are not meant to be changed. That's the whole idea about id keys: values that say nothing about the data, so they should not change.

    But if you have to, you could rely on ON triggers. And triggers have a history that doesn't recommend them for this job at all, keeping together the data integrity.

  3. #3
    SitePoint Wizard guelphdad's Avatar
    Join Date
    Oct 2003
    Location
    St. Catharines, ON Canada
    Posts
    1,708
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you use LAST_INSERT_ID to get the value inserted in the article table and use that to insert into the images table.

  4. #4
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    ^ Right you are. I misread what the OP was asking. Sorry.

    I don't use or recommend LAST_INSERT_ID myself, but that's another story altogether.

  5. #5
    SitePoint Member
    Join Date
    May 2012
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by guelphdad View Post
    you use LAST_INSERT_ID to get the value inserted in the article table and use that to insert into the images table.
    BIG THANKS to you. I solved my problem tyty!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •