当我在搜索框中搜索单词时,如果单词不在我的数据库中,我想添加他给出建议,如果单词已经在数据库中,我只想更新搜索次数这个词可以成为最流行的词汇的顶部。
就像谷歌一样。搜索框有效,但我不知道如何在每次提取行时只插入一次单词。
$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);
}
}
答案 0 :(得分:4)
在单词字段上添加UNIQUE
键,然后:
INSERT INTO table (...)
VALUES (...)
ON DUPLICATE KEY UPDATE field=field+1