繁体   English   中英

Mysql,检查行是否存在,是否确实获取值,如果不存在则插入

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM