简体   繁体   中英

Using PDO to insert multiple records in multiple tables from one statement?

Im trying to build a form to allow binding of keywords to articles. This SQL statement works directly as a query but I dont know how to package it as a pdo statement. It adds the keyword to a Keyword Table and Keyword ID + Article ID to a many to many mapping table.

$insertK = $dbh->prepare("INSERT IGNORE INTO Keywords (Keyword)
VALUES (:KeywordID1);
INSERT INTO Keyword_Article (KeywordID, ArticleID)
VALUES ((SELECT KeywordID FROM Keywords WHERE Keyword = :KeywordID2), :ArticleID)");

$insertK->bindParam(':KeywordID1',  $keywordID);
$insertK->bindParam(':KeywordID2',  $keywordID);
$insertK->bindParam(':ArticleID',  $articleID);
$insertK->excecute();

Ive seen PDO inserts a few different ways but none that do two statements into two different tables.

EDIT* If its not possible then how could I make sure that the first insert is finished before running the second query?

This is quite common misconception.
For some reason people constantly trying to stuff as many queries in one call as possible.
While there is actually no reason at all.

Just run all your queries one by one usual way.
There is absolutely nothing wrong with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM