gpt4 book ai didi

php - 如果条件为真但不是在每一行都为真,如何插入或更新?

转载 作者:太空宇宙 更新时间:2023-11-03 10:47:26 24 4
gpt4 key购买 nike

当我在搜索框中搜索一个词时,如果这个词不在我的数据库中我想添加他来提供建议,如果这个词已经在数据库中我只想更新搜索次数那个词 to 可以成为最流行的词的顶部。

这就像谷歌。搜索框可以工作,但我不知道如何只插入一次这个词,而不是每次获取行时。

$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);
}
}

最佳答案

在word字段上添加一个UNIQUE键,然后:

INSERT INTO table (...)
VALUES (...)
ON DUPLICATE KEY UPDATE field=field+1

关于php - 如果条件为真但不是在每一行都为真,如何插入或更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29638621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com