我有兩個表,一個是存儲「tid」(自動增量)和「name」(標籤名稱)的'tags'。第二個表「tags_data」存儲每個標籤上的數據。這張表的字段是「tid」(來自第一張表)和其他幾個字段。Mysql,檢查是否存在行,如果它確實抓取值,如果沒有插入
這樣人們可以在我的網站上標記內容。當我標記內容時,我想首先檢查該標記是否已經存在於第一個表中。如果它不存在,那麼我們將標籤插入數據庫並使用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在線使用指南,但似乎無法正常工作。
看到這個帖子就會解決這個問題[這裏是鏈接](http://stackoverflow.com/questions/12436602/if-exists-update-else -insert-haunted-me-for-hours-new-to-mysql/12437127#12437127) –