繁体   English   中英

如何使用PHP和Mysql检查数据库中是否已存在相同的标签?

[英]How do I check if the same tag was already in database with PHP and Mysql?

我希望此脚本检查是否输入了相同的单词,因此应将其添加到计数中而不添加重复的标签。

如果输入的标签是新标签,则将其添加到数据库中。

有人可以帮我解决这个问题吗?

$tag = mysql_real_escape_string($_POST['tag']);
$query = "INSERT INTO tags (tag, count) VALUES ('$tag', 1)
          ON DUPLICATE KEY UPDATE count = count+1";
if (!mysql_query($query, $dbc))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($dbc)

谢谢每个人都能工作,但又遇到了另一个问题,但这是一个不同的问题

尝试此查询将主键添加到标签表

ALTER TABLE tags  ADD PRIMARY KEY (tag);

UPDATE

只需在phpmyadmin中运行它,或者

做这个

$sql = "ALTER TABLE tags  ADD PRIMARY KEY (tag)";
$result = mysql_query($sql);

在一个test.php中

更新2

好的,这意味着您已经有了主键,您可以使用此查询现在添加唯一索引以标记。

ALTER TABLE标记添加唯一(标记);

请注意,如果您已经有重复项,则需要先将其删除。

当然,这很容易。 在数据库的“标签”列上添加唯一索引或使其成为主键。

您的问题是id可能是主键,而不是标签。 正如我上面提到的,您的代码仅在标签是表上的主键时才有效

您说表的结构如下:

id    tag    count

这意味着除非您将tag作为主键,否则当前查询将无法工作。 如果是这种情况,您可能id列用作主键。

因此,请放轻松,然后检查该标签是否已经存在。

如果是这样,请更新计数。 如果没有,请添加它。

//--grab the tag
$tag = mysql_real_escape_string($_POST['tag']);

//--see if the tag already exists and potentially what the current count is
$query = "SELECT id, count FROM tags WHERE tag='$tag'";
$result = mysql_query($query);

//--if there is a row, that means the tag exists
if(mysql_num_rows($result))
{
//--pull out the tag ID and the current count and increment by one.
  $tag_info = mysql_fetch_array($result);
  $tag_info_id = $tag_info["id"];
  $tag_info_count = $tag_info["count"] + 1;

//--update the table with the new count
  $sql_update_cnt = "UPDATE tags SET count='$tag_info_count' 
                            WHERE id='$tag_info_id'";
  mysql_query($sql_update_cnt);

  echo "$tag now with $tag_info_count instances";
}
else
{
//--tag is not there, so insert a new instance and 1 as the first count
  $query = "INSERT INTO tags (tag, count) VALUES ('$tag', 1)";
  mysql_query($query);

  echo "1 record added";
}

mysql_close($dbc);

如果您使用的是mySQL,则可以使用INSERT ON DUPLICATE KEY语法,只要您的标记名是主键(或唯一键)

INSERT INTO `tags` (`tag`, `count`)
VALUES ($tag, 1)
    ON DUPLICATE KEY UPDATE `count`=`count`+1;

在表上添加主键,请使用:

ALTER TABLE `tags` ADD PRIMARY KEY (`tag`)

但是您不需要id列,因为您可以将标记名用作主键

ALTER TABLE `tags` DROP COLUMN `id`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM