简体   繁体   中英

Linking existing MySQL records in new query, PHP/PDO

$insert = $dbh->prepare('INSERT INTO tags (tag_name) VALUES (:tag)');
  $insert->bindParam(':tag', $tag, PDO::PARAM_STR);
  foreach($tags as $tag) {
   $insert->execute();
   $tag_id = $dbh->lastInsertID();
echo $tag_id."+".$photo_id."<br />";
$sql = "INSERT INTO tagrefs (tag_id, photo_id) VALUES (:tag_id,:photo_id)";
$q = $dbh->prepare($sql);
$q->execute(array(':tag_id'=>$tag_id,
                       ':photo_id'=>$photo_id));
  }

This particular piece of code inserts tags related to uploaded photos into a table called 'tags'. It links the tag_id to the photo_id in a table called 'tagrefs'. This all works fine, until I use a tag twice. Which is logical, because nothing is inserted (tags are unique, I simply want the entry in 'tagrefs' to list the photo_id for my next photo with tag_id's that already exist)

How do I make it so that my code compares the tags the user put in and compares them, or that the values of existing tags are returned and put into 'tagrefs' properly? Thank you very much in advance for your time.

If you use INSERT ... ON DUPLICATE KEY UPDATE , then lastInsertID() will return the AUTO_INCREMENT field's value of a matched row even if an UPDATE is performed instead of an insertion.

To ensure that it also works in versions of MySQL prior to v5.1.12, one can explicitly set the insertion id with MySQL's LAST_INSERT_ID() function:

INSERT INTO tags
  (tag_name)
VALUES
  (:tag)
ON DUPLICATE KEY UPDATE
  id = LAST_INSERT_ID(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