MySQL 数据库条目重复
我有一个 PHP 脚本搜索脚本,它记录在 MySQL 数据库中进行的每个查询,值列中以 1 开头。目前,如果相同的术语被搜索多次,则值列中的数字将加 1。但是,在两次搜索同一单词后,该查询将再次添加到数据库中。为什么会这样呢?
我的 PHP 代码是:
<?php
$database=mysql_connect("localhost","username","password");
mysql_select_db("database",$database);
$query=$_GET['q'];
logQuery($query);
function logQuery($query){
$query="insert into queries (query) values ('$query') on duplicate key update value=value+1";
mysql_query($query);
}
?>
I have a PHP script search script that logs every query made in a MySQL database starting with 1 in the value column. Currently, if the same terms are searched more than once, 1 is added to the number in the value column. However, after two searches for the same word, the query gets added to the database again. Why could this be?
My PHP code is:
<?php
$database=mysql_connect("localhost","username","password");
mysql_select_db("database",$database);
$query=$_GET['q'];
logQuery($query);
function logQuery($query){
$query="insert into queries (query) values ('$query') on duplicate key update value=value+1";
mysql_query($query);
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来好像
query
不是您的主键,或者 $query 与数据库内容不同。我的钱在钥匙上;它可以是复合键吗?即id
和query
?在这种情况/示例中,必须使用 mysql_escape_string(trim($query)) 来避免 SQL 注入。
Sounds like either
query
is not your primary key, or that $query is different from the DB contents. My money is on the key; could it be a composite key? i.e.id
ANDquery
?In this situation/example, using
mysql_escape_string(trim($query))
is a MUST to avoid SQL injection.如果第二次添加查询,那么它显然不是主键,这会阻止“重复键”工作
If the query is getting added a second time, then it is obviously not a primary key, which prevents the 'on duplicate key' from working
您是否将查询字段定义为唯一?也许是空格之类的,尝试使用 md5 作为唯一键
Do you define query field as unique? maybe a whitespace or something, try using md5 as unique key