I want to combine these two queries into one:
mysql_query("INSERT INTO categories (name, parent) VALUES ('$name', '$parent')");
mysql_query("UPDATE categories SET 开发者_如何转开发child='$child' WHERE ID = $id");
Can it be done?
Create a trigger in MySQL.
Without doing any checking on if a parent category exists, or catching exceptions the following should do the trick. Replace 'dbname' with whatever your db is.
DROP TRIGGER IF EXISTS `dbname`.`update_parent`//
CREATE TRIGGER `dbname`.`categories` AFTER INSERT ON `dbname`.`categories`
FOR EACH ROW BEGIN
UPDATE categories SET child = NEW.ID WHERE ID = NEW.parent;
END
//
When the trigger is functioning correctly, the update will get called automatically after an INSERT
so all you have to do is run:
mysql_query("INSERT INTO categories (name, parent) VALUES ('$name', '$parent')");
Although I don't know if this fits your problem, in fact it is possible to combine multiple queries into one, by using the MySQLi extension (it will not work with mysql extension)
mysqli_multi_query($connection, "INSERT INTO a (attrib1, attrib2) VALUES ('$a', '$b');UPDATE b SET attrib3='$c' WHERE attrib4 = $d");
精彩评论