1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Rep Power

    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.

    $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?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Mar 2008
    Rep Power
    Insert Ignore

  4. #3
  5. Hockey face
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    St. Catharines, Canada
    Rep Power
    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.

IMN logo majestic logo threadwatch logo seochat tools logo