September 29th, 2012, 04:45 PM
-
Checking for existence of multiple terms using single query possible?
I want to check for the existence of each tag in a tags array. If it doesn't exist, I insert the tag into the MySql database.
Code:
$tags = $_POST['tags'];
$tags = explode(',', $tags);
// Check if each tag exist
$query = "";
$num = count($tags);
for($i = 0; $i < $num; $i++) {
$tag = $tags[$i];
$tag = mysql_real_escape_string($tag);
$query = "SELECT tag FROM tags WHERE LOWER('tag') = LOWER('".$tag."')";
$result = mysql_query($query);
if(!$result) {
// Do mysql insertion here
}
}
This may be bad for performance as I am executing a statement for each tag. So if a user enters 10 tags. I'd loop through each tag and then do a query and execute the statement for each tag. I was wondering if there is a better way to achieve what I want. Like for example, combine all the queries into 1 single query then executing just one statement?
September 29th, 2012, 06:16 PM
-
September 29th, 2012, 06:44 PM
-
Use INSERT IGNORE syntax (see the manual if you don't know it). Then you don't have to check if the tag exists you just try to enter it. if it is already in the database the INSERT is IGNOREd.