2010-05-23 41 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