php,sql有趣的查询选项

时间:2010-11-11 17:42:16

标签: php sql wordpress

    <input type="checkbox" name="average" value="average" <? if (get_option('average') == 'average'){ echo 'checked="checked"';} ?>>Average

    <input type="checkbox" name="petite" value="petite" <? if (get_option('petite') == 'petite'){ echo 'checked="checked"';} ?>>Petite



     if ( get_option('average') == 'average' ): // choose category
    $average = "AND build = '".get_option('average')."'";
    endif;

    if ( get_option('petite') == 'petite' ): // choose category
    $petite = "OR build = '".get_option('petite')."'";
    endif;


    $qry = mysql_query("SELECT performerid,pic0 FROM ".$table." WHERE **$average $petite** ORDER BY RAND() LIMIT 20");

如何使此代码有效?我需要sql查询才能工作,如果选择$ average,选择$ average和$ petite,还是只选择$ petite?

TY!

2 个答案:

答案 0 :(得分:1)

你可以使用这样的东西:

$selectedCategories = array();
foreach(array('petite', 'average', 'athletic') as $category)
{
  if (get_option($category) == $category)
  {
    $selectedCategories[] = $category;
  }
}

$qry = mysql_query(
 "SELECT performerid,pic0 
    FROM ".$table." 
   WHERE build IN('" . implode("', '", $selectedCategories) . "') 
ORDER BY RAND() LIMIT 20;");

注意:如果您不选择任何类别,这将不起作用。

答案 1 :(得分:0)

你需要使用php函数isset();

if(isset($_POST)){ //checks if post is set
    if(isset($)POST['average']) && !isset($_POST['petite'])){
        //do staff only average is set
    }
    elseif(isset($_POST['petite']) && !isset($_POST['average'])){
        //do staff only petite is set
    }
    elseif(isset($_POST['average'] && isset($_POST['average']))){
        //do staff both is set
    }

}