如何在数组中使用where语句

时间:2015-10-14 07:18:19

标签: php mysql

**我想使用条件数组检索品牌名称以创建json格式。但是,我无法得到它。结果是“没有找到记录。我怎么能这样做?**

<?

    $brand_array=array('sony','samsung');                  
        $data=implode(',',$brand_array);        
        $query_brand=mysql_query("SELECT ttdbrand.name
                                  FROM `taxonomy_term_data` as ttdbrand
                                  INNER JOIN
                                        `node` as n
                                  INNER JOIN        
                                        `field_data_field_brand` as fbrand
                                  ON n.nid=fbrand.entity_id
                                  AND ttdbrand.tid=fbrand.field_brand_tid                                 
                                  Where ttdbrand.name in ('$data')"                                              
                                  ) or die(mysql_error()) ;


        while($row = mysql_fetch_assoc($query_brand)) {         
            $row_array[]=$row;                 
        }
?>

3 个答案:

答案 0 :(得分:0)

而不是数组使用类似值的字符串      你的用户数组('a','b','c');

 run this array and make string 
 $str = '';
 e.g while (your array)
    $srt .= '\''.$value.'\''.',';

    $str look like 'a','b','c',

 after loop is over remove ',' rtrim and user this $str variable insted of $data 

答案 1 :(得分:0)

替换此处,在引号

中排列字符串
 $data=implode(',',array_map(function($v){return "'".$v."'"},$brand_array));  

答案 2 :(得分:0)

它不起作用,因为:

Where ttdbrand.name in ('$data')

将导致此:

Where ttdbrand.name in (sony,samsung)   
//no quotation marks. you can't pass strings like that, sql will fail  

与@MarkBaker一样,你需要添加如下引号:

$data=implode("','",$brand_array);