2

So I have a dynamic built query using the 'IN' clause, but really need to select for two parameters, and cannot seem to figure out how to do this.

$selectSql= "SELECT groupid FROM groups WHERE name IN(";

foreach ($groupsArray as $group => $row){

  $selectSql .= "'".$row['name']."'".",";

}  
$selectSql = rtrim($selectSql, ',');
$selectSql .= ")";

Really, the query needs to look something like:

$selectSql= "SELECT groupid FROM groups WHERE name and type IN(;

How would I go about doing this?

Sincere thanks for any help! it is greatly appreciated.

2
  • 1
    now what is your present output? Commented Feb 3, 2015 at 9:36
  • What you are doing has nothing to do with prepared statement. Please remove the tag. Commented Feb 3, 2015 at 9:36

2 Answers 2

3

Try implode()

foreach ($groupsArray as $group => $row ){
  $name[]= "'".$row['name']."'";
  $type[] = "'".$row['type']."'";
}  
$selectSql= "SELECT groupid FROM groups WHERE name IN(".implode(',',$name).") and type IN(".implode(',',$type).")";
Sign up to request clarification or add additional context in comments.

Comments

2

I also support implode() but done in a slightly different way:

$name = array();
$type = array();
foreach ($groupsArray as $group => $row ) {
  $name[] = $row['name'];
  $type[] = $row['type'];
}

$selectSql= "SELECT groupid FROM groups WHERE name IN ('". implode("' ,'", $name) ."') and type IN ('". implode("', '", $type). "')";

In this way you do not have to change the array to insert the ' to each item because it is done by implode.

I did not understand well what he's like your array, but you may even direct access $groupsArray items without creating $name and $type.

Comments

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.