我有数据库表:images和category
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; } }
我有一种形式来输入标题和插入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; } }
几件事:
for
VALUES()
$images
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(); }