使用数组循环MySQL Where语句

时间:2010-05-23 16:23:13

标签: php loops

我正在尝试创建一个循环,它将为MySQL查询输出多个where语句。最终,我的目标是最终得到这四个单独的Where语句:

`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` = ''

有没有人看到我做错了什么?感谢。

2 个答案:

答案 0 :(得分: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]."` = ";

答案 1 :(得分: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);

干杯,
费边