【发布时间】:2012-10-31 17:32:42
【问题描述】:
我有两个表,一个是存储“tid”(自动增量)和“name”(标签名称)的“标签”。第二个表“tags_data”存储每个标签上的数据。此表包含字段“tid”(来自第一个表)和其他一些字段。
这样人们就可以在我的网站上标记内容。当我标记内容时,我想首先检查该标记是否已存在于第一个表中。如果它不存在,那么我们将标签插入数据库并使用 tid 插入第二个表。到目前为止,我已经完成了这部分工作。
问题是当标签已经存在于数据库中时,我想抓取现有的 tid 并在我的第二个查询中使用它。
这是我目前的代码:
// check if tag already exists
$tagexists = "SELECT COUNT(*) as cnt FROM tags WHERE 'name' = '$usetag' LIMIT 1";
$results = mysql_query($tagexists) or die('Invalid query: ' . mysql_error());
if ($results['cnt'] == 0) {
// tag is not yet in DB
$tagquery1 = "INSERT INTO tags (name) VALUES ('$usetag')";
$result = mysql_query($tagquery1) or die('Invalid query: ' . mysql_error());
$lastid = mysql_insert_id();
$tagquery2 = "INSERT INTO tags_data (tid, nid, uid) VALUES ($lastid, $nid2, $uid)";
$result = mysql_query($tagquery2) or die('Invalid query: ' . mysql_error());
} else {
// tag is already in DB, grab the tid
$grabtid = "SELECT tid FROM tags WHERE 'name' = '$usetag' LIMIT 1";
$results = mysql_query($grabtid) or die('Invalid query: ' . mysql_error());
$row = mysql_fetch_array($results);
$lastid = $row['tid'];
$tagquery2 = "INSERT INTO tags_data (tid, nid, uid) VALUES ($lastid, $nid2, $uid)";
$result = mysql_query($tagquery2) or die('Invalid query: ' . mysql_error());
}
我检查标签是否已经存在的方式有问题。我正在使用 COUNT 在线遵循指南,但它似乎无法正常工作。
【问题讨论】:
-
看这篇文章会解决这个问题Here is link