I know this is a pretty old question that's already been answered, but a friend of mine helped set up a database with a "constraint" where an insert or update had to have 1 value match one value from a different table in the same database exactly in order to fire off.
I'm not very good with MySQL calls yet so I don't understand exactly what it does... but it may help you cut down on the code necessary to do what you want?
(Note: I had to modify it a bit to remove some sensitive names & such from it, but it should be a good representation.)
-- -----------------------------------------------------
-- Table `db1`.`table1`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db1`.`table1` (
`id` INT NOT NULL AUTO_INCREMENT ,
`av_key` VARCHAR(40) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `db1`.`table2`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `db1`.`table2` (
`bkid` INT NOT NULL AUTO_INCREMENT ,
`id` INT NOT NULL ,
`data` VARCHAR(6144) NULL ,
PRIMARY KEY (`bkid`) ,
INDEX `id_idx` (`id` ASC) ,
CONSTRAINT `id`
FOREIGN KEY (`id` )
REFERENCES `db1`.`table1` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
With this, you just need to do the insert/update statement, and it'll just fail if there's no match for "id" in both tables.
Don't know if you already found out or if that's what you needed, but figured it was worth sharing!