[英]Mysql, Check if row exists, if it does grab value, if not insert
我有兩個表,一個是存儲“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在線跟蹤指南,但它似乎沒有正常工作。
$results['cnt'] == 0
錯了。 你忘了得到結果。 ($ results是資源ID。)
if(mysql_result($results) == 0){
同樣,你獲取現有數據的if
第二部分也會丟失它。 你想使用$data = mysql_fetch_assoc($result);
那里。
我認為你的代碼是錯誤的
$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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.