Implement it in a stored procedure (the table is called ibt, which stands between the table):
delimiter ;
DROP TABLE IF EXISTS `ibt`;
CREATE TABLE `ibt` (
`seqid` int(10) unsigned NOT NULL auto_increment,
`article_id` varchar(10) NOT NULL default '',
`user_id` varchar(10) NOT NULL default '',
anotherVar VARCHAR(10),
PRIMARY KEY (`article_id`,`user_id`),
KEY `seqid` (`seqid`)
) ENGINE=MEMORY AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
drop procedure if exists addEntry;
delimiter $$
create procedure addEntry(_article_id INT, _user_id INT, _anotherVar VARCHAR(10))
begin
DECLARE done INT DEFAULT 0;
declare seq INT;
declare seqNew INT DEFAULT 1;
declare Cnt INT DEFAULT 0;
declare cur CURSOR for
SELECT seqid
from ibt
where user_id=_user_id
order by seqid desc;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
START TRANSACTION;
open cur;
REPEAT
FETCH cur INTO seq;
IF NOT done THEN
SET Cnt = Cnt+1;
IF Cnt = 3 THEN
DELETE FROM `ibt` where seqid = seq;
END IF;
IF Cnt = 1 THEN
SET seqNew = seq + 1;
END IF;
END IF;
UNTIL done END REPEAT;
INSERT into `ibt`
SET article_id=_article_id,
user_id=_user_id,
seqid=seqNew,
anotherVar=_anotherVar;
close cur;
COMMIT;
end $$
delimiter ;
call addEntry(1, 1, 'a');
call addEntry(2, 1, 'b');
call addEntry(3, 1, 'c');
call addEntry(4, 1, 'd');
You can run the above SQL as a unit for testing. I used HeidiSQL.
Once you have a stored procedure in your database, you can "call addEntry" from your PHP code.