I'm using PHP/MySql.
If I have two tables (hypothetically) as follows:
id
name
and
parent_id
action
And id in the first table is set to AUTO_INCREMENT, if I wanted to insert data into both tables in as fewer queries as possible without re-structuring the database, how could I go about this? I need the next A_I value that will be given to the name that is inserted into table one to insert as the parent ID for the second table.
Probably a poor example, but it's a problem I'm trying to solve. At the minute I'm having to do the following:
<?php
$mysqli->query("INSERT INTO table_1 (name) VALUES ('Bob');
$names = $mysqli->query("SELECT * FROM table_1 WHERE name = 'Bob'");
while($name = $names->fetch_assoc()) {
$mysqli->query("INSERT INTO table_2 (parent_id, action) VALUES ('".$name['id']."', 'run')");
}
?>
But obviously this method breaks if there are people with the same name.
Thanks.
All you need is http://php.net/manual/en/mysqli.insert-id.php
<?php
$mysqli->query("INSERT INTO table_1 (name) VALUES ('Bob')");
$mysqli->query("INSERT INTO table_2 (parent_id, action) VALUES ($mysqli->insert_id,'run')");
?>
You can use PHP function $mysqli->insert_id
or MySQL function last_insert_id()
I would do it this way:
$mysqli->query("INSERT INTO table_1 (name) VALUES ('Bob')");
$mysqli->query("INSERT INTO table_2 (parent_id, action) VALUES (LAST_INSERT_ID(),'run')");