带有PDO的多次插入 [英] Multiple inserts with PDO
本文介绍了带有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;
}
}
我有一个输入标题的表格,并可以插入url图片.
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
循环迭代器为$images
数组编制索引或使用foreach
- 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的多次插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文