[英]How to insert or update if a condition is true, but not at every row?
When I search for a word in the searching box, if the word is not in my database I want to add him for giving suggestions, and if the word is already in the database I just want to update the number of searches of that word to can make a top of most popular words. 当我在搜索框中搜索单词时,如果该单词不在我的数据库中,我想添加他以提供建议,并且如果该单词已经在数据库中,我只想将该单词的搜索次数更新为可以成为最受欢迎的单词的开头。
It's like Google. 就像Google。 The search box works but I don't know how to insert the word just one time not every time the rows are fetched.
搜索框可以工作,但我不知道如何仅一次插入单词,而不是每次都提取行时才插入。
$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);
}
}
Add a UNIQUE
key on the word field, and then: 在单词字段上添加一个
UNIQUE
键,然后:
INSERT INTO table (...)
VALUES (...)
ON DUPLICATE KEY UPDATE field=field+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.