在INSERT之前验证一个条件中的多行

时间:2016-06-03 16:12:31

标签: php mysql

我有桌子产品:

 - id: int 
 - name: varchar(255)
 - articles_id  : int (foreign key)
 - number_document : varchar(255)

我有表格文章:

 - id_article: int
 - name_article : varchar(255)

插入产品时,我通过选择多个选项选择了一个或多个项目。   但是当我在同一产品中插入一篇或多篇文章时,我会检查已经存在的各种项目,例如:

product1, name1, articles1, number_doc1
product1, name1, articles2, number_doc1
product1, name1, articles3, number_doc1

我不会在同一产品中插入这些商品

$num_doc= $_GET['doc'];
$sql = $db->query("SELECT * FROM product WHERE document_number ='".$num_doc."'");

while ($var2 =  $sql->fetch(PDO::FETCH_ASSOC)) { 
    $a =   $var2['articles_id'];
    $b =   $var2['name']; 
    $c =   $var2['number_document']; 

    if (!empty($_POST['do'])) {
        $articles_id = $_POST["articles_id"];
        foreach ($articles_id as $art) {
            if ($a == $art) {
                echo 'already exist';
            } else {
                $sql = $db->query("INSERT INTO product(articles_id, name, document_number) values ('".$art."', '".$b."', '".$c."')");
            }
        }   
    }              
}

<form action ="POST">
    <div id="step-2">
        </br></br>
        <div class="col-md-9 col-sm-9 col-xs-12" style="height: 300px">
            <label class="control-label col-md-3 col-sm-3 col-xs-12">Article <span class="required">*</span></label>
            <div class="col-md-9 col-sm-9 col-xs-12">
                <select class="select" style="width: 500px;position: absolute;margin-left: 500px" name="articles_id[]" multiple="multiple">
                <?php
                $sql='SELECT * FROM articles ';
                $list = $db->query($sql);
                while ($data = $list->fetch(PDO::FETCH_ASSOC)) {
                    echo'<option value="'.$data['id_articles'].'">&nbsp;&nbsp;&nbsp;'.$data['name_articles'] .'  '.$data['code_articles'].'</option>';
                }
                ?>
                </select>
            </div>
        </div>
        </br></br></br></br>
        <div class="form-group">
            <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
                <button type="reset" class="btn btn-primary" onclick="self.location.href='addInputs.php'">Non</button>
                <button type="submit" class="btn btn-success" name ="do" value="update">Valider</button>
            </div>
        </div>
    </div>
</form>But it inserted the same article that existed.  How do I prevent that? 

1 个答案:

答案 0 :(得分:1)

尝试,

$sql = $db->query("INSERT IGNORE INTO product(articles_id, 
name, document_number) values ('".$art."', '".$b."', '".$c."')");

http://dev.mysql.com/doc/refman/5.7/en/insert.html

  

如果使用IGNORE关键字,则执行时会出现错误   INSERT语句被忽略。例如,没有IGNORE,就是一行   复制表中的现有UNIQUE索引或PRIMARY KEY值   导致重复键错误,语句被中止。同   IGNORE,该行被丢弃,不会发生错误。忽略错误   而是生成警告。

我会发布更多链接来帮助你,但有很多。搜索&#34; php INSERT IGNORE INTO&#34;或者只是自己搜索$sql = $db->query("INSERT IGNORE INTO并获得大量点击。