使用PDO从一条语句在多个表中插入多个记录? [英] Using PDO to insert multiple records in multiple tables from one statement?

查看:99
本文介绍了使用PDO从一条语句在多个表中插入多个记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一种表单,以允许将关键字绑定到文章.该SQL语句直接用作查询,但我不知道如何将其打包为pdo语句.它将关键字添加到关键字表,将关键字ID +文章ID添加到多对多映射表.

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();

我已经看到PDO插入了几种不同的方法,但是没有一种方法可以在两个不同的表中执行两个语句.

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.

这篇关于使用PDO从一条语句在多个表中插入多个记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆