我有一个带标签名称的输入,它们之间有空格。然后我将它分解为一个数组,并在每个标记中循环遍历数组。如果标签不存在,我希望它添加到我的标签表中,并再次添加到我的coupon_tags表中。如果它存在,只需coupon_tags表。我的代码在一次处理一个标签时起作用,但是多标签处理它破坏了。无论是否存在标记,我的代码总是会说它存在,这意味着它会看到包含该标记的行数的非零结果。
也许有一种更简单的方法来测试MySQL表中某些东西的存在,而不是我是如何做到的(选择包含tagName的所有行,然后查看行数是1还是0) ?
我有以下代码:
$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 :(得分:1)
$splitTags = explode(" ", $tag);
foreach ($splitTags as $key=>$val)
{
// replace $splitTags[$i] with $val
...
}
答案 1 :(得分:0)
$splitTags = explode(" ", $tag);
...返回一个数组。
foreach($splitTags as $i){
此行开始遍历数组中的每个条目。
所以,这样做:$splitTags[$i]
是错误的。
您需要做的就是参考$i
;
P.S。检查一下这是为了保护自己免受注射:http://php.net/manual/en/function.mysql-real-escape-string.php
答案 2 :(得分:0)
只需选择一个虚拟值,然后检查是否有一行,不需要计算总行数。 E.g。
$ res = mysql_query(SELECT 1 FROM tags WHERE tagName ='sometag'); if(mysql_num_rows($ res)== 0){// do 插入..
此外,如果您的输入来自用户,请确保转义WHERE子句输入
$ res = mysql_query(“SELECT 1 FROM tags WHERE tagName ='“。mysql_real_escape_string($ tags [i])。”'“);
否则您可能容易发生SQL注入攻击