本文介紹了帶 PDO 的多個刀片的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有數據庫表:images
和 category
目前唯一插入到類別表的函數是這樣的:
Currently the only function to insert in category table is similar to this:
public function add($ttitle)
{
try
{
$stmt = $this->db->prepare("INSERT INTO category (title) VALUES(:title)");
$stmt->bindparam(":title",$ttitle);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
我有一個表格可以輸入標題和插入網址圖片的可能性.
I have a form to enter title and the possibility of inserting urls images.
通過單擊提交標題,我想轉到類別表,到目前為止還可以,圖像應該轉到表圖像,每個圖像都有一個 id,但內部連接到類別的 id.
By clicking on the submit the title I want to go to the category table, so far ok, images should go to the table images, an id for each image but with inner join to the id of the category.
表格images
:
id_image | category_id | dir_image
我無法正確執行此操作
$stmt = $this->db->prepare("INSERT INTO category (title) VALUES(:ttitle)");
$stmt = $this->db->prepare("SELECT id_image FROM images WHERE id_category = category_id ");
我想要的結果示例:
html 表單
Category title: Test
Image1: image1.png
Image2: image2.png
Image3: image3.png
Image4: image4.png
Submit
提交后
表格類別:
id_category | title
1 Test
表格圖片:
id_image | category_id | dir_image
1 1 image1.png
2 1 image2.png
3 1 image3.png
4 1 image4.png
<小時>
更新:
public function add($ttitle,$images)
{
try {
$stmt = $this->db->prepare("INSERT INTO category (title) VALUES(:title)");
$stmt->bindparam(":title",$ttitle);
$stmt->execute();
$lastId = $db->lastInsertId();
$imgs = count($images);
for ($i = 0; $i < $imgs; $i++){
$stmt = $this->db->prepare("INSERT INTO images (category_id, dir_image) VALUES (:title)");
$stmt->bindparam(":category_id",$lastId);
$stmt->bindparam(":dir_image",$images);
$stmt = $this->db->prepare($sql);
$stmt->execute()
}
return true;
}
catch(PDOException $e) {
echo $e->getMessage();
return false;
}
}
推薦答案
幾件事:
- 刪除
for
循環中的第二個prepare語句 - 在sql語句的
VALUES()
中添加綁定參數 - 使用
for
循環迭代器或使用foreach
索引
$images
數組- Remove the second prepare statement inside
for
loop - Add binded params into the
VALUES()
of sql statement - Index the
$images
array withfor
loop iterator or useforeach
查看調整后的for
循環:
$stmt = $this->db->prepare("INSERT INTO images (category_id, dir_image)
VALUES (:category_id, :dir_image)");
$stmt->bindParam(":category_id" ,$lastId);
$stmt->bindParam(":dir_image", $image);
for ($i = 0; $i < count($images); $i++){
$image = $images[$i];
$stmt->execute();
}
或者使用 foreach
循環 (假設是一維數組):
$stmt = $this->db->prepare("INSERT INTO images (category_id, dir_image)
VALUES (:category_id, :dir_image)");
$stmt->bindParam(":category_id", $lastId);
$stmt->bindParam(":dir_image", $item);
foreach ($images as $item){
$stmt->execute();
}
這篇關于帶 PDO 的多個刀片的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!