2016-09-20 79 views
0

我有數據庫,在mysql中保存我的數據。 我已經有數據在我的表(呼叫字),我想插入新的數據到這張表,但在我想檢查這個數據是否不存在之前。 我有功能,插入數據表,但我需要sql查詢,將檢查數據不存在? 我的表'詞'中的列是:單詞,數字,命中,instoplist。 我用PHP編寫的代碼插入值表,如果行不存在

感謝,

這是我的代碼:(插入到表函數)

function insert($myWords) 
    { 
     global $conn; 
     $temp1 = $value['document']; 
     $temp2 = $value['word']; 

      $sql = "INSERT INTO words (word,num,hit,instoplist) VALUES"; 
      foreach ($myWords as $key => $value) { 
       $word = $value['word']; 
       $number = $value['document']; 
       $hit = $value['hit']; 
       $stop = $value['stopList'];   
       $sql .= "('$word', '$number', '$hit','$stop'),";     
      } 
      $sql = rtrim($sql,','); //to remove last comma 
      if($conn->query($sql)!== TRUE) 
      { 
         echo "error". $conn->error; 
      } 
    } 
+0

爲什麼不讓「字」字是唯一的? –

+0

你想插入一行,如果不存在,否則更新該行,對不對? –

+0

,因爲我有幾行同一個字在不同的文檔中 – adi

回答

0

插入數據做出一列是作爲唯一一個選擇查詢之前按您的要求,如:

$chkExist = "select id from table where col_name = '".$value."'"; 
$res = $conn->query($chkExist); 

// Now check if there is some record in $res than stop the entry otherwise insert it 
+0

我不能使用unik,因爲我在不同的行中使用相同的單詞 – adi

-1
$sel="select * from words where word = '$word' AND document = '$document' AND hit = '$hit' AND stopList ='$stopList'"; 
    $qry=mysqli_query($sel); 
    $num=mysqli_num_rows($qry); 
if($num==0){ 
    $sql = "INSERT INTO words (word,num,hit,instoplist) VALUES"; 
     foreach ($myWords as $key => $value) { 
      $word = $value['word']; 
      $number = $value['document']; 
      $hit = $value['hit']; 
      $stop = $value['stopList'];   
      $sql .= "('$word', '$number', '$hit','$stop'),";     
     } 
     $sql = rtrim($sql,','); 
    }else{ 
     echo "Already Exist"; 
    } 
+1

如果您使用mysql_ *'它已棄用並在php 7中關閉,OP也不使用它。 OP如何維護連接? – devpro

+0

感謝您的更新,PLZ閱讀,如何mysqli_ *工程http://php.net/manual/en/mysqli.query.php,您提供的代碼不能工作 – devpro

+0

好的謝謝。我沒有在我的代碼中使用這個。 – premi

0
function insert($myWords) 
{ 
    global $conn; 
    $temp1 = $value['document']; 
    $temp2 = $value['word']; 

     $sql = "INSERT INTO words (word,num,hit,instoplist) VALUES"; 
     foreach ($myWords as $key => $value) { 
      $sql2 "SELECT * FROM words WHERE word = '".$value['word']."' OR num = '".$value['document']."'"; //other data if you want 
      $resultat=mysql_query($query); 
      if($resultat==""){ 
       $word = $value['word']; 
       $number = $value['document']; 
       $hit = $value['hit']; 
       $stop = $value['stopList'];   
       $sql .= "('$word', '$number', '$hit','$stop'),"; 
      }    
     } 
     $sql = rtrim($sql,','); //to remove last comma 
     if($conn->query($sql)!== TRUE) 
     { 
        echo "error". $conn->error; 
     } 
}