我有一个输入,它带有标签名称,它们之间有空格。然后,我将它分解成一个数组,并在每个标记中遍历数组。如果标签不存在,我希望它添加到我的标签表中,并再次添加到我的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')");
}
你脆弱的时刻SQL注入。只是FYI。 – clifgriffin 2011-02-16 20:09:46