0

I have have a multi-select feature which allows the user to tag a company with services. And in my database I have a table with just id and names of those services. What I am trying to do is create a statement that searches to see if the tag already exists, if it does not exist, create it. Could someone help me with the logic of setting this up?

I am just not sure how to go about searching through a table column with an array.

Thanks

$company_type = implode(',', $company_type);
 $lookup_tags = "SELECT * FROM table WHERE company_type_id = ?";
  $q_lookup_tags = $conn->prepare($lookup_tags);
   $q_lookup_tags -> execute(array($company_type));

How do I perform the select and sort the results into existing and non existing ids?

Thanks

2 Answers 2

1

mysql in operator is your friend here:

$lookup_tags = "SELECT * FROM table WHERE company_type_id in ($company_type)";

but if you're using pdo prepared statements you'll need to filter manually

Edit

$placeHolders=implode(',',array_fill(0,count($company_type),'?'));
$lookup_tags = "SELECT * FROM table WHERE company_type_id in ($placeHolders)";
$qry= $conn->prepare($lookup_tags);
$qry->execute(array_values($company_type));
Sign up to request clarification or add additional context in comments.

1 Comment

which I did point out in the original answer. Edited with a safer version
0
 $query = "";
 $i = 0;
 foreach($company_type as $key=>$type){
    $query.="SELECT $type as type, count(*) as total,* FROM table WHERE company_type_id = ".intval($type);
    if($i < count($company_type)){
        $query.=" UNION ";
    } 
    $i++;
}

$q_lookup_tags = $conn->prepare($query);
$q_lookup_tags -> execute();

2 Comments

just about the second part of the question how would I go about sorting the existing and non existing tags? Usually I perform a row count after a select statement to see if it exists but I have never tried to pass an array through before
you could use mysql union statement and craft a query. I'll edit my post, give me a sec.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.