这个问题已经有了答案:
Insert multiple rows with PDO
1个答案
我有数据库表:images
和category
当前在类别表中插入的唯一函数类似于:
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;
}
}
我有一个表格输入标题和可能插入的网址图片。
通过单击submit the title,我想转到category表,到目前为止,ok,images应该转到images表,每个图像都有一个id,但是内部连接到category的id。
表格:
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()
中
使用循环迭代器索引$images
数组。
参见调整后的循环:
$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();
}
或者使用
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", $item);
foreach ($images as $item){
$stmt->execute();
}
关于php - 带PDO的多个插入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43730736/