Generate query for names linked to attributes

from the Artful MySQL Tips List


<?php

/*
  PHP script to generate a query for names in a parent table 
  for which there are matching values in an attributes table
 */
$a = array( 'red''orange''long' );
$n count$a );
$qry "SELECT DISTINCT p.name FROM parents p JOIN attributes a ON p.id=a.id WHERE a.attributevalue IN(";
for( 
$i=0$i<$n$i++ ) {
  
$qry .= "'" $a[$i] . "'" . (( $i $n-) ? "," ")");
}
echo 
$qry;
/*
  Generates: 
  SELECT DISTINCT p.name FROM parents p JOIN attributes a ON p.id=a.id 
  WHERE a.attributevalue IN('red','orange','long')
 */

?>


Return to the Artful MySQL Tips page