小编典典

带有PDO的多个插入

mysql

我有数据库表:imagescategory

当前,唯一要插入类别表的函数与此类似:

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图像的可能性。

通过单击提交标题,我要转到类别表,到目前为止,图像应该转到表图像,每个图像都有一个ID,但内部连接到该类别的ID。

桌子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;
    }

}

阅读 302

收藏
2020-05-17

共1个答案

小编典典

几件事:

  1. for循环内删除第二个prepare语句
  2. 将绑定的参数添加到VALUES()sql语句中
  3. $images使用for循环迭代器索引数组或使用foreach

请参阅调整后的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();
}
2020-05-17