2016-04-27 50 views
-1

我想確保沒有任何日期雙重預訂。我已經使用了select distinct和insert查詢來調用數據。但仍然可以複製數據。兩個查詢截然不同,並插入給出錯誤

這裏是整個代碼:

<?php 
       error_reporting(0); 

        $con=mysqli_connect("localhost","root","","jpn"); 
        [email protected]$_POST["rol_no"]; 
        [email protected]$_POST["ic"]; 
        [email protected]$_POST["tarikh"]; 
        [email protected]$_POST["tarikhakhir"]; 
        [email protected]$_POST["bilangan"]; 
        [email protected]$_POST["sebab"]; 
//insertion data tempahan 
        $sql="INSERT INTO tempahan(ic,start,end,bil,title) VALUES ('$ic','$start','$end','$bil','$title') 
        ON DUPLICATE KEY 
        UPDATE 
        ic='$ic' 
        ,start ='$start' 
        ,end='$end' 
        ,bil='$bil' 
        ,title='$title' 
        "; 

$result=mysqli_query($con,$sql); 

        if($row=mysqli_fetch_array($con,$result)) 
        { 
         $rol_no=$row[0]; 
         $ic=$row[1]; 
         $start=$row[2]; 
         $end=$row[3]; 
         $bil=$row[4]; 
         $title=$row[5]; 

        } 
//distinct data to avoid duplicate for date 
        $sql2= "SELECT DISTINCT start, end 
         FROM tempahan 
         ORDER BY start, end"; 
        if(mysqli_query($con,$sql2)) 
        { 
         echo "<script>alert('duplicate tarikh')</script>"; 
        } 
?> 
+0

[RTFM on'mysqli_fetch_array()'。](http://php.net/manual/en/mysqli-result.fetch-array.php) –

回答

0

使用唯一字段/字段集的唯一索引。它是必需的並且足以保證唯一性。然後,使用IGNORE選項或ON DUPLICATE KEY UPDATE進行插入。沒有獨特的索引他們不工作。