2010-05-23 70 views
0

我想创建一个循环,将输出MySQL查询的多个where语句。最终,我的目标是与这四个独立的,语句来结束:使用数组循环通过MySQL在哪里陈述

`fruit` = '1' AND `vegetables` = '1' 
`fruit` = '1' AND `vegetables` = '2' 
`fruit` = '2' AND `vegetables` = '1' 
`fruit` = '2' AND `vegetables` = '2' 

我的理论的代码粘贴如下:

<?php 

$columnnames = array('fruit','vegetables'); 
$column1 = array('1','2'); 
$column2 = array('1','2'); 

$where = ''; 
$column1inc =0; 
$column2inc =0; 

while($column1inc <= count($column1)) { 
    if(!empty($where)) 
    $where .= ' AND '; 
    $where = "`".$columnnames[0]."` = "; 
    $where .= "'".$column1[$column1inc]."'"; 

    while($column2inc <= count($column2)) { 
     if(!empty($where)) 
     $where .= ' AND '; 
     $where .= "`".$columnnames[1]."` = "; 
     $where .= "'".$column2[$column2inc]."'"; 

      echo $where."\n"; 

    $column2inc++; 
} 

$column1inc++; 
} 

?> 

当我运行这段代码,我得到以下输出:

`fruit` = '1' AND `vegetables` = '1' 
`fruit` = '1' AND `vegetables` = '1' AND `vegetables` = '2' 
`fruit` = '1' AND `vegetables` = '1' AND `vegetables` = '2' AND `vegetables` = '' 

有没有人看到我在做什么不正确?谢谢。

回答

1

我的建议如下代码:

$columnnames = array('fruit','vegetables'); 
$column1 = array('1','2'); 
$column2 = array('1','2'); 

$list = array(); 
for($i = 0; $i < count($column1); $i++) { 
     for($k = 0; $k < count($column2); $k++) { 
       $str = sprintf("`%s` = `%d` AND `%s` = `%d`", 
         $columnnames[0], 
         $column1[$i], 
         $columnnames[1], 
         $column2[$k] 
       ); 
       $list[] = $str; 
     } 
} 

echo implode(' AND ', $list); 

干杯,
费边

+0

这段代码很有趣。虽然它将所有4个语句合并为一个,但它看起来正在做我想要的东西。我会操纵一下,看看会发生什么。感谢您清理我的代码。 – Ryan 2010-05-23 16:43:33

1

永不复位$where

顺便说一句。不要做

if(!empty($where)) 
$where .= ' AND '; 
$where = "`".$columnnames[0]."` = "; 

因为这是危险的含糊不清。做

if(!empty($where)) $where .= ' AND '; 
$where = "`".$columnnames[0]."` = "; 

if(!empty($where)) { 
    $where .= ' AND '; 
} 
$where = "`".$columnnames[0]."` = "; 
+0

疑难杂症,谢谢! – Ryan 2010-05-23 16:44:32