php拼接多个insert,php – 将多个INSERTS分成一个表和多个表
我正在嘗試使用PostgreSQL數據庫在 PHP中開發一個Q& A網站.
我有一個動作來創建一個頁面,其中包含標題,正文,類別和標簽.我設法插入所有這些字段,但是我在插入多個標記值時遇到了一些問題.
我使用這個函數將逗號分隔的值放到一個數組中,現在我想要一些東西將每個數組元素插入到表標記的數據庫中(避免重復),然后插入我的多對多關系表問題標簽:
$tags = explode(',', $_POST['tags']); //Comma separated values to an array
打印這樣的東西:
Array ( [0] => hello [1] => there [2] => this [3] => is [4] => a [5] => test )
動作/ create_question.php
$category = get_categoryID_by_name($_POST['category']);
$question = [
'userid' => auth_user('userid'),
'body' => $_POST['editor1'],
'title' => $_POST['title'],
'categoryid' => $category
];
create_question($question, $tags);
然后我的create_question我應該插入標簽.
function create_question($question, $tags) {
global $conn;
$query_publications=$conn->prepare("SELECT * FROM insert_into_questions(:body, :userid, :title, :categoryid);
");
$query_publications->execute($question);
}
我在考慮做這樣的事情:
全球$conn;
foreach ($tags as $tag) {
$query_publications=$conn->prepare("INSERT INTO tags(name) VALUES($tag);
");
$query_publications->execute($question);
}
但后來我需要在我的多對多表中插入標簽id.我是否需要創建另一個過程get_tags_id然后獲取tag_id數組并在我嘗試標記時插入它們?
我什么時候執行查詢?插入后或彼此結束?
對于任何誤用的術語或我的新手問題,我們深表歉意.我是PHP的新手,我正在努力解決一些新概念.
最佳答案 您可以使用CTE在一個SQL命令中完成所有操作.
假設Postgres 9.6和這個經典的多對多模式(因為你沒有提供它):
CREATE TABLE questions (
question_id serial PRIMARY KEY
, title text NOT NULL
, body text
, userid int
, categoryid int
);
CREATE TABLE tags (
tag_id serial PRIMARY KEY
, tag text NOT NULL UNIQUE);
CREATE TABLE questiontags (
question_id int REFERENCES questions
, tag_id int REFERENCES tags
, PRIMARY KEY(question_id, tag_id)
);
要使用標記數組插入單個問題:
WITH input_data(body, userid, title, categoryid, tags) AS (
VALUES (:title, :body, :userid, :tags)
)
, input_tags AS ( -- fold duplicates
SELECT DISTINCT tag
FROM input_data, unnest(tags::text[]) tag
)
, q AS ( -- insert question
INSERT INTO questions
(body, userid, title, categoryid)
SELECT body, userid, title, categoryid
FROM input_data
RETURNING question_id
)
, t AS ( -- insert tags
INSERT INTO tags (tag)
TABLE input_tags -- short for: SELECT * FROM input_tags
ON CONFLICT (tag) DO NOTHING -- only new tags
RETURNING tag_id
)
INSERT INTO questiontags (question_id, tag_id)
SELECT q.question_id, t.tag_id
FROM q, (
SELECT tag_id
FROM t -- newly inserted
UNION ALL
SELECT tag_id
FROM input_tags JOIN tags USING (tag) -- pre-existing
) t;
dbfiddle here
這會創建任何尚未存在的標記.
Postgres數組的文本表示如下所示:{tag1,tag2,tag3}.
如果保證輸入數組具有不同的標記,則可以從CTE input_tags中刪除DISTINCT.
詳細說明:
> Insert data in 3 tables at a time using Postgres
> How to use RETURNING with ON CONFLICT in PostgreSQL?
> How to implement a many-to-many relationship in PostgreSQL?
> Cannot INSERT: ERROR: array value must start with “{” or dimension information
如果您有并發寫入,則可能需要執行更多操作.特別考慮第二個鏈接.
總結
以上是生活随笔為你收集整理的php拼接多个insert,php – 将多个INSERTS分成一个表和多个表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Matlab中的logspace函数,m
- 下一篇: php hash pbkdf2,PHP