使用-table item_image-将表单中的值插入到我的mysql-lastInsertId()-中时遇到问题

这是我的数据库

item table
id(auto increment,Primary key)
item_name (varchar)
item_description (tinytext)
item_price(varchar)
item_date(date)

item_image
itemId(PRIMARY KEY),
small_image(varchar),
big_image(varchar)


这是我的表格

<form method="post" action="?<?php echo $action;?>">
<p>
<label for="item_name">Name of Article :</label>
<input type="text" name="item_name" id="item_name" value="" />
</p>

<p>
<label for="item_description">Short Description:</label>
<textarea id="item_description" name="item_description" rows="3" cols="40" value=""></textarea>
 </p>

<p>
<label for="">Item small Image :</label>
<input type="text" id="small_image" name="addimages[]" value="" />
</p>

<p>
<label for="">Item small Image:</label>
<input type="text" id="big_image" name="addimages[]" value="" />
</p>

<div>
<input type="submit" name="submit" id="submit" value="<?php echo $button;?>" />
</div>


在此我们拥有PHP代码

if (isset($_GET['addform'])) {
$item_name = trim($_POST['item_name']);
$item_description = trim($_POST['item_description']);
$item_price = trim($_POST['item_price']);

 try {

$sql = 'INSERT INTO items SET
        item_name = :item_name,
        item_description = :item_description,
        item_price = :item_price,
        item_date= CURDATE()';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':item_name', $item_name);
$stmt->bindValue(':item_description', $item_description);
$stmt->bindValue(':item_price', $item_price);
$stmt->execute();
 }
  catch (PDOException $e) {
   echo "Something went wrong".$e->getMessage();
 }

$itemId = $pdo->lastInsertId();

  if (isset($_POST['addimages'])) {

    $add_images = $_POST['addimages'];

    try {
      $sql ='INSERT INTO item_image SET
              itemId = :itemId,
             small_image = :small_image,
             big_image = :big_image';
      $stmt = $pdo->prepare($sql);
         foreach ($add_images as $add_image) {
           $stmt->bindValue(':itemId', $itemId);
           $stmt->bindValue(':small_image', $add_image[0]);
           $stmt->bindValue(':big_image', $add_image[1]);
           $stmt->execute();
         }
    }
      catch (PDOException $e) {
      echo "Sth got wrong with the query".$e->getMessage();
    }
  }


我遇到的问题是:所有值都插入了items表中,但是对于item_image表...我遇到了这个错误:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '30' for key 'PRIMARY'

我正在搜索,但是找不到问题。我的foreach循环似乎是正确的。

我想做的是:将lastInsertId()值和addimages array values插入我的item_image表中

可以帮忙..谢谢。

最佳答案

您已经为itemId表中的item_image列设置了唯一索引,但是根据您提供的信息,您的商品可以具有多个图像,因此itemId表中的多个item_image列可以具有相同的值(引用“父”图像的ID),并且不应该在此处使用唯一索引。为该列使用普通索引。

关于php - 我如何解决此错误:SQLSTATE [23000]:违反完整性约束:1062键“PRIMARY”的条目“30”重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33752912/

10-11 13:32