I have an input that takes tag names, with a space between them. Then I explode it into an array and loop through the array once per tag. If the tag doesn’t exist, I want it added to my tags table, and again to my coupon_tags table. If it exists, just the coupon_tags table. My code worked when it handled one tag at a time, but with multi-tag handling it broke. No matter the existence of a tag, my code will always say that it exists, which means that it sees a non-zero result for the amount of rows containing that tag.
Perhaps there is an easier way to test for the existence of something in a MySQL table, rather than how I did it (selecting all rows that contain the tagName I have, then seeing if the amount of rows is one or zero)?
I have the following code:
$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')");
}
1 Answer