Reputation: 10340
I have a table named tags
like this:
/ tags
+----+------+--------------------------------------------+
| id | name | explanation |
+----+------+--------------------------------------------+
| 1 | PHP | It is a server-side scripting language |
| 2 | C++ | It is a middle-level programming language |
| 3 | HTML | It is a markup language |
| 4 | CSS | It is a style sheet language |
| 5 | JS | It is a prototype-based language |
+----+------+--------------------------------------------+
Also I have a string like this:
$str = "PHP , CSS";
Now I need to check whether both PHP
and CSS
are exist in the database? In general there is two cases:
True
: All tags in the string are exist in the database.False
: One or more of tags in the string doesn't exist in the database.I can explode that string and create a array of those tags:
$tags = trim(explode(",",$str)); // Array ( [0] => PHP [1] => CSS )
And then create multiple queries to check each of them separately:
$i= count($tags);
for($i; $i <= 0; $i--){
$query .= "SELECT count(1) FROM `tags` WHERE `name` =".$tags[$i]." UNION ALL";
}
$query = rtrim($query, "UNION ALL"); // to remove last 'UNION ALL' which is redundant
But my approach seems really slow .. Because sometimes there is 5 tags (then there is 5 queries). Now I want to know, is there any better way?
Upvotes: 0
Views: 158
Reputation: 772
You can try this:
SELECT COUNT(name),name FROM `tags` WHERE name in ('PHP','CSS') group by name;
Upvotes: 0
Reputation: 9583
You can do this thing such a way. Try this:
Your New Query:
$str = "PHP , CSS";
$search = join(",", trim(explode(",",$str)));
$sql = "SELECT count(1) FROM `tags` WHERE `name` IN ($search)";
$qry = mysql_query($sql);
if(sizeof($qry) == sizeof(explode(",",$str)))
echo "True";
else
echo "False";
I think now you can do it.
Upvotes: 2
Reputation: 31739
You can also use IN('PHP', 'CSS') and check the count matches or not. Try -
$tags = explode(",",$str);
$tags = array_map('trim', $tags);
$query = "SELECT count(1) FROM `tags` WHERE `name` IN ('" . implode("','", $tags) . "')";
After executing the query match the counts.
if($countOfResult === count($tags));
Upvotes: 1