php - how to get id of unique column -
- insert article , find tags in it
- insert 1 tag , 1 reference 1 one know last_insert_id() of tag
$tags = array('strawberries','blueberries','food','strawberries') function hashtaginsert($tags) { /// commit transaction $lastinsertid = $this->db->lastid(); // last insert id of article foreach ($tags $val) { $sql = 'insert tags (tag, added) values (:tag, now()) on duplicate key update occurrence = occurrence + 1'; $this->db->boolquery($sql, array(':tag' => $val)); $sql2 = 'insert tags_refs (article_id, tag_id) values (:lastinsertid, last_insert_id())'; $this->db->boolquery($sql2, array(':lastinsertid' => $lastinsertid)); } }
i wrote script take care of it. , works. unfortunately there bit problem duplicities because there unique column.
if there duplicity there origin tag , don't know id has. in table after have got new reference last insert tag doesn't exist.
the tag exists reference wrong.
the db looks after first processing script:
create table `tags` ( `id` int(11) not null auto_increment, `tag` varchar(100) not null, `occurrence` int(11) not null, `added` datetime not null, primary key (`id`), unique key `tag` (`tag`) ) engine=myisam default charset=utf8; insert `tags` (`id`, `tag`, `occurrence`, `added`) values (18, 'boobs', 1, '2015-05-29 16:46:44'), (20, 'food', 0, '2015-05-29 16:46:44'), (19, 'blueberries', 0, '2015-05-29 16:46:44'); , reference one: drop table if exists `tags_refs`; create table `tags_refs` ( `id` int(11) not null auto_increment, `article_id` int(11) not null, `tag_id` int(11) not null, primary key (`id`) ) engine=myisam default charset=utf8; insert `tags_refs` (`id`, `article_id`, `tag_id`) values (24, 31, 18), (25, 31, 19), (26, 31, 20), (27, 31, 26); -- 2015-05-29 14:49:55
function hashtaginsert($tags) { /// commit transaction $lastinsertid = $this->db->lastid(); foreach ($tags $val) { $sql = 'insert tags (tag, added) values (:tag, now()) on duplicate key update occurrence = occurrence + 1, last_article_id = :lastinsertid'; $stmt = $this->db->boolquery($sql, array(':tag' => $val, ':lastinsertid' => $lastinsertid)); if(!$stmt) { $sql3 = 'select id tags tag = :tag'; $existingtagid = $this->db->queryfetch($sql3, array(':tag' => $val)); } $tagid = (isset($existingtagid)? $existingtagid : $this->db->lastid()); $sql2 = 'insert tags_refs (article_id, tag_id) values (:lastinsertid, :tagid)'; $this->db->boolquery($sql2, array(':lastinsertid' => $lastinsertid, ':tagid' => $tagid)); unset($existingtagid); } }
Comments
Post a Comment