[英]How to insert or update if a condition is true, but not at every row?
當我在搜索框中搜索單詞時,如果該單詞不在我的數據庫中,我想添加他以提供建議,並且如果該單詞已經在數據庫中,我只想將該單詞的搜索次數更新為可以成為最受歡迎的單詞的開頭。
就像Google。 搜索框可以工作,但我不知道如何僅一次插入單詞,而不是每次都提取行時才插入。
$cuvant=$_GET['cuvant']; //the word that I introduce in the searching box
$sql="SELECT * from cautare";// cautare is the table where I keep the words
$resursa=mysql_query($sql); //the resource
while($row = mysql_fetch_array($resursa)) {
$nr=$row['nr_cautari'];//number of serching of each word
if ($row['cuvant']!=$cuvant && $cuvant!=''){//if the word is not in the database i want to insert him
$nr=1;
$sql2="INSERT INTO cautare values('".$cuvant."',".$nr.")";
$resursa2=mysql_query($sql2);
}else if($row['cuvant']==$cuvant && $cuvant!=''){ //if the word is in the database i just want to uptdate the number_of_searches field
$nr=$nr+1;
$sql3="UPDATE cautare set nr_cautari=".$nr."where cuvant='".$cuvant."'";//update the number_of_searches field
$resursa3=mysql_query($sql3);
}
}
在單詞字段上添加一個UNIQUE
鍵,然后:
INSERT INTO table (...)
VALUES (...)
ON DUPLICATE KEY UPDATE field=field+1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.