我希望此脚本检查是否输入了相同的单词,如果是,则应将其添加到计数中,而不是添加重复的标记。
如果输入的标签是新标签,则让它将其添加到数据库中。
有人可以帮我解决这个问题吗?
$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)
感谢每一个人我都要工作,但是另一个问题可能会起来,但这是一个不同的问题
答案 0 :(得分:3)
尝试此查询以将主键添加到代码表
ALTER TABLE tags ADD PRIMARY KEY (tag);
<强>更新强>
只需在phpmyadmin OR中运行
这样做
$sql = "ALTER TABLE tags ADD PRIMARY KEY (tag)";
$result = mysql_query($sql);
在test.php中
更新2
好的,这意味着您已经有了主键,现在可以使用此查询为标记添加唯一索引。
ALTER TABLE标签ADD UNIQUE(tag);
请注意,如果您已经有重复项,那么您需要先删除它们。
答案 1 :(得分:2)
当然,这很容易。在数据库中的“tag”列上添加唯一索引或将其设为主键。
答案 2 :(得分:0)
你的问题是id可能是主键,而不是标签。正如我上面提到的,只有当tag是表中的主键时,你的代码才会起作用
答案 3 :(得分:0)
你说你的表结构如下:
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);
答案 4 :(得分:0)
如果您正在使用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`