相同的条形码意外插入我的数据库

时间:2017-10-03 09:15:10

标签: php mysqli

这是用于将条形码插入数据库的代码,但如果数据库中存在相同的条形码,我不需要再次插入相同的条形码,所以我这样编码但是,相同的条形码是插入我的数据库。这段代码中的错误是什么?

我正在使用mysqli和Bootstrap来显示页面中的错误,该页面是通过ajax从另一个名为product.php的页面执行的,它在另一个名为showuser.php的页面中显示,因为它在表格中得到更新给出输出

<?php
        include('conn.php');

        if(isset($_POST['add'])){
            $proname=$_POST['product'];
            $bar=$_POST['barcode'];
            $war=$_POST['warranty'];
            $gar=$_POST['guarranty'];
            $amount=$_POST['amount'];
            $id = $_POST['cusid'];
            $date = $_POST['date'];

            $check = "SELECT * FROM warranty_update WHERE battery_serial = '$bar'";
            $rs = mysqli_query($con,$check);
    $data = mysqli_fetch_array($rs, MYSQLI_NUM);
    if($data[0] > 1) {

    ?>
        <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>


        <h3 align="center"><i class="   glyphicon glyphicon-warning-sign"></i><br>
    <br>
      Sorry Barcode Already Been Inserted !<br><br>

    Please Go Back</h3>
    <?php } else {

         $datesplit     = explode("-",$date);
         $warranty      = $datesplit[0];
         $guarante      = $datesplit[0];


         $day    = $datesplit[1];
         $month  = $datesplit[2];

          $fdate =  strtotime($date);
          $Gm=strtotime("+$gar Months",$fdate);
          $wm=strtotime("+$war Months",$Gm);
            $m1=date("Y-m-d", $Gm) ;
            $m2 =date("Y-m-d", $wm) ;

         $today =  date("Y/m/d");


          $expiry_warranty = $m2;
          $expiry_guarante = $m1;

        //mysql_query("INSERT INTO `cus_reg`(`reg_id`, `name`, `mobile`, `battery_serial`, `model`, `date`, `reg_by`, `warranty_expiry`, `waranty_span`,`guarantee_expiry`, `g_span`) VALUES (NULL,'$name','$mobile','$battery_serial','$vehicle_num','$date','$regby','$expiry_warranty', '$wmonth', '$expiry_guarante', '$gmonth')")==true or die(mysql_error);


            //mysql_query("INSERT INTO `warranty_update`(`wa_id`, `cus_reg_id`, `new_barcode`, `date`) VALUES (NULL,LAST_INSERT_ID(),'$battery_serial','$today')");

    mysqli_query($conn,"INSERT INTO `warranty_update`(`wa_id`, `reg_id`, `battery_serial`, `model`, `date`, `warranty_expiry`, `waranty_span`, `guarantee_expiry`, `g_span`, `amount`) VALUES (NULL,'$id','$bar','$proname','$today','$expiry_warranty','$war','$expiry_guarante','$gar','$amount')");  
    mysqli_query($conn,"INSERT INTO `replacements`(`r_id`, `reg_id`, `wa_id`, `new_barcode`, `date`) VALUES ('NULL','$id',LAST_INSERT_ID(),'$bar','$today')");  
       ?>


       <!--header("refresh:1;url=home.php");-->

         <h3 align="center"><i class="  glyphicon glyphicon-warning-sign"></i><br>
    <br>
      Data Successfully Inserted !  


    <?php }


        }
    ?>

2 个答案:

答案 0 :(得分:2)

不完全确定,但你应该检查这样的数组是否有条目:

if (count($data) > 0)

答案 1 :(得分:1)

执行此操作的最佳方法是通过SQL定义条形码的唯一约束。 无论如何,我认为你是在错误的模式下评估条件。 $ data是一个数组,所以你应该用sizeof检查他的大小。

所以:if(sizeof($data) > 1) { .... }