参见英文答案 >
Insert multiple rows with PDO1个
我有数据库表:图像和类别
我有数据库表:图像和类别
目前,在类别表中插入的唯一功能类似于:
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; } }
我有一个表单输入标题和插入网址图像的可能性.
通过点击提交标题我想转到类别表,到目前为止,图像应该转到表格图像,每个图像的ID,但内部联接到类别的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; } }
几件事:
原文链接:https://www.f2er.com/php/138348.html>删除for循环中的第二个prepare语句
>将绑定参数添加到sql语句的VALUES()中
>使用for循环迭代器索引$images数组或使用foreach
请参阅adjust for loop:
$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,$item); foreach ($images as $item){ $stmt->execute(); }