开发者

Checking the existence of a string in a MySQL table

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 h开发者_如何学Candled 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')");
}


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


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

...returns an array.

foreach($splitTags as $i){

This line starts going through each entry in the array.

So, doing this: $splitTags[$i] is wrong. All you need to do is reference $i;

P.S. Check out this for protecting your self against injection: http://php.net/manual/en/function.mysql-real-escape-string.php


Just select a dummy value and then check whether you got a row back, no need to count the total number of rows. E.g.

$res = mysql_query(SELECT 1 FROM tags WHERE tagName = 'sometag'); if(mysql_num_rows($res) == 0) { // do insert ..

Also, if your input is coming from the User then make sure you escape your WHERE clause input

$res = mysql_query("SELECT 1 FROM tags WHERE tagName = '" . mysql_real_escape_string($tags[i]) . "'");

Otherwise you might be prone to SQL injection attacks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜