I want to insert multiple rows into different tables in my database. The statements are paired, where the second relies on data (specifically LAST_INSERT_ID()) from the first statement.
This code works, but I wonder if it can be done in a better way?
Is there a way to have it all in one single query?
<?php
mysql_query("
INSERT INTO wp_terms (term_id, name, slug, term_group)
VALUES ('', 'Test 1', 'test-1', '0')
");
mysql_query("
INSERT INTO wp_term_taxonomy (term_taxonomy_id, term_id, taxonomy, description, parent, count)
VALUES ('', LAST_INSERT_ID(), 'mycustomfield', 'Descripton 1', '0', '0')
");
mysql_query("
INSERT INTO wp_terms (term_id, name, slug, term_group)
VALUES ('', 'Test 2', 'test-2', '0')
");
mysql_query("
INSERT INTO wp_term_taxonomy (term_taxonomy_id, term_id, taxonomy, description, parent, count)
VALUES ('', LAST_INSERT_ID(), 'mycustomfield', 'Descripton 2', '0', '0')
");
mysql_query("
INSERT INTO wp_terms (term_id, name, slug, term_group)
VALUES ('', 'Test 3', 'test-3', '0')
");
mysql_query("
INSERT INTO wp_term_taxonomy (term_taxonomy_id, term_id, taxonomy, description, parent, count)
VALUES ('', LAST_INSERT_ID(), 'mycustomfield', 'Descripton 3', '0', '0')
");
mysql_query("
INSERT INTO wp_terms (term_id, name, slug, term_group)
VALUES ('', 'Test 4', 'test-4', '0')
");
mysql_query("
INSERT INTO wp_term_taxonomy (term_taxonomy_id, term_id, taxonomy, description, parent, count)
VALUES ('', LAST_INSERT_ID(), 'mycustomfield', 'Descripton 4', '0', '0')
");
?>
If it is a thing to reduce the call of
mysql_query, Yes, There is a way but you have to use themysqlifor this.The mysqli::multi_query can execute the multiple queries in once.