如何使用'IN'运算符在Mysql查询中使用数组值?

时间:2012-10-16 17:14:05

标签: php mysql

$_POST['domain']是某种形式的CHECKBOX的结果,其中包含3个或更多域的值(C,C ++,Java等),其值现在保存在数组'$Domain'中。现在,我需要从我的表中选择与CHECKBOX中用户选择的域相同的元组。

我尝试使用FOR循环,但它给了我一个T_FOR例外    错误或其他什么。现在我正在尝试使用内爆函数,它不是    给出任何查询错误但不显示查询的任何结果    无论是! PROBLEM位于查询的IN运算符中。怎么样    我可以解决吗?

if(isset($_POST['domain']))
    {
        $Domain = $_POST['domain'];
        $search=$_POST['search'];

        $N = count($Domain);

        echo("<p>You selected $N domain(s):<br/><br/> ");
        for($i=0; $i < $N; $i++)
        {
            echo($Domain[$i] . "<br/> ");
        }
        echo("</p>");

        $dom_str="'".implode("', '",$Domain)."'";

    $query ="SELECT * FROM learner_object WHERE(lo_tag1='$search' || lo_tag2='$search' || lo_tag3='$search') AND 
            lo_domain IN ( ".$dom_str." ) ";

    $result =mysql_query($query)
    or die('query failed.'.mysql_error());

      while($row = mysql_fetch_array($result))
        {   
            echo  "<a href=\" ".$row['lo_url']." \" target=\"_blank\" \">"  .   $row['lo_name']  .   "</a> <br/> ";     
            echo $row['lo_desc']."<br/><br/>";      
        }
     }
     else
     echo "<p>You didn't select any Domain.</p><br/>";

3 个答案:

答案 0 :(得分:1)

试试这个,

  $dom_str=!empty($Domain)?implode(",",$Domain):'default value';

$query ="SELECT * FROM learner_object WHERE(lo_tag1='$search' || lo_tag2='$search' || lo_tag3='$search') AND 
        lo_domain IN ($dom_str)";

答案 1 :(得分:0)

$dom = implode (',',$Domain);  
$query ="SELECT * FROM learner_object WHERE(lo_tag1='$search' || lo_tag2='$search' || lo_tag3='$search') AND 
        lo_domain IN ( ".$dom." ) ";

答案 2 :(得分:0)

感谢大家帮助我。我已经在你的帮助下找到了正确的代码。 查询: -

$query ="SELECT * FROM learner_object WHERE(lo_tag1='$search' || lo_tag2='$search' || lo_tag3='$search') AND lo_domain IN ( '" . implode("','", array_map('trim', $Domain)) ."' ); ";