我有数据库表: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;
}
}
我有一个表格可以输入标题和插入网址图片的可能性。
通过点击提交标题我想转到类别表,到目前为止,图像应该转到表格图像,每个图像的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;
}
}
答案 0 :(得分:0)
有几件事:
for
循环VALUES()
$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();
}