2011-02-16 41 views
0

我有一个输入,它带有标签名称,它们之间有空格。然后,我将它分解成一个数组,并在每个标记中遍历数组。如果标签不存在,我希望它添加到我的标签表中,并再次添加到我的coupon_tags表中。如果存在,只需要coupon_tags表。我的代码每次处理一个标签时都有效,但多标签处理打破了。无论标签是否存在,我的代码都会说它存在,这意味着它看到包含该标签的行数量的非零结果。检查MySQL表中字符串的存在

也许有一种更简单的方法来测试MySQL表中是否存在某些东西,而不是我如何做到这一点(选择包含tagName的所有行,然后查看行数是否为零或零)?

我有以下代码:

$splitTags = explode(" ", $tag); 

foreach($splitTags as $i){ 
    echo $splitTags[$i] . "<br/>"; 
    $resTags = mysql_num_rows(mysql_query("SELECT * FROM tags WHERE tagName = '$splitTags[$i]'")); 
//if tag doesn't already exist, create it. either way, append this coupon's id to the list id's related to this tag and add a space 
    if($resTags > 0) 
    { 
     $tagQueRes = mysql_query("SELECT tagID FROM tags WHERE tagName = '$splitTags[$i]'"); 
     $row = mysql_fetch_assoc($tagQueRes); 
     $tagID = $row["tagID"]; 
     echo "Tag Exists" . "<br/>"; 
    } 
    else 
    { 
     $tagID = mysql_num_rows(mysql_query("SELECT * FROM tags")) + 1; 
      mysql_query("INSERT INTO tags (tagName, tagID) VALUES ('$splitTags[$i]','$tagID')"); 
     echo "New Tag Added" . "<br/>"; 
    } 
    mysql_query("INSERT INTO coupon_tags (tagID, couponID) VALUES ('$tagID', '$newID')"); 
} 
+0

你脆弱的时刻SQL注入。只是FYI。 – clifgriffin 2011-02-16 20:09:46

回答

1
$splitTags = explode(" ", $tag); 
foreach ($splitTags as $key=>$val) 
{ 
    // replace $splitTags[$i] with $val 
    ... 
} 
0

只需选择一个虚拟值,然后检查你是否得到了一个行,无需计算总行数。例如。

$ res = mysql_query(SELECT 1 FROM tags WHERE tagName ='sometag'); 如果(mysql_num_rows($水库)== 0){//做 插入..

另外,如果您的输入来自用户请确认您逃避你的WHERE子句输入

$解析度=请求mysql_query( “选择1 FROM标签 WHERE的tagName = '” mysql_real_escape_string($标签[I])。 “'”);

否则,你可能容易受到SQL注入式攻击