Reputation: 99
I need to do an inner join with the insert into statement. I need to insert data into 2 tables but the id of the records from the second table should also be stored into a column from the first table.
the first sql section makes a new record for every given dj name in the dj table, the second part is supposed to get the id from the added dj and insert it into a column from table "articles".
$alle_djs = explode(', ', $this->djs);
foreach ($alle_djs as $elke_dj) {
$sql = "INSERT INTO dj (name) VALUES ( :name_dj )";
$st = $conn->prepare($sql);
$st->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
$st->execute();
$sql2 = "INSERT INTO articles (dj_ids) SELECT id FROM dj WHERE name=:name_dj";
$st2 = $conn->prepare($sql2);
$st2->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
$st2->execute();
}
$conn = null
Upvotes: 1
Views: 1253
Reputation: 781721
Use the LAST_INSERT_ID()
function:
$sql2 = "INSERT INTO articles(dj_ids) VALUES (LAST_INSERT_ID())";
Upvotes: 2