2012-10-31 22 views
0

我有兩個表,一個是存儲「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在線使用指南,但似乎無法正常工作。

+0

看到這個帖子就會解決這個問題[這裏是鏈接](http://stackoverflow.com/questions/12436602/if-exists-update-else -insert-haunted-me-for-hours-new-to-mysql/12437127#12437127) –

回答

1

$results['cnt'] == 0是錯誤的。你忘了得到結果。 ($結果是資源ID。)

if(mysql_result($results) == 0){ 

同樣,你那得到現有數據丟失它太if的第二部分。你想在那裏使用$data = mysql_fetch_assoc($result);

+0

我的代碼似乎有其他問題。即使標籤已經存在,它似乎不在乎,它只是再次插入它。有什麼其他的東西對你而言? 編輯:似乎圍繞'名稱'的單引號使計數爲0.刪除它們修復它,謝謝 – Jay

+0

第二部分似乎不起作用(如果標記存在) – Jay

+1

第一個查詢中再次出現單引號在第二部分。是否還有其他錯誤? – AndrewR

1

我覺得你的代碼是錯誤的

$tagexists = "SELECT COUNT(*) as cnt FROM tags WHERE 'name' = '$usetag' "; 
$res = mysql_query($tagexists) or die('Invalid query: ' . mysql_error()); 
$results = mysql_fetch_assoc($res); 
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());   
} 
+0

建議使用mysql_fetch_assoc(及其變體) –

相關問題