Php 使用数组循环遍历MySQL Where语句
我试图创建一个循环,为MySQL查询输出多个where语句。最终,我的目标是以以下四个独立的Where语句结束:Php 使用数组循环遍历MySQL Where语句,php,loops,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` = '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++;
}
?>
有人看到我做错了什么吗?谢谢。您永远不会重置
$where
顺便说一句,不要这样做
if( !empty( $where ) )
$where .= ' AND ';
$where = "`".$columnnames[0]."` = ";
因为这是危险的模棱两可。做
if( !empty( $where ) ) $where .= ' AND ';
$where = "`".$columnnames[0]."` = ";
或
我建议使用以下代码:
$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);
$columnnames=array('fruit','vegets');
$column1=数组('1','2');
$column2=数组('1','2');
$list=array();
对于($i=0;$i
干杯,费边这段代码很有趣。虽然它将所有4条语句合并为一条语句,但它似乎在做我想做的事情。我来操纵一下,看看会发生什么。谢谢你清理了我的代码。
if( !empty( $where ) ) {
$where .= ' AND ';
}
$where = "`".$columnnames[0]."` = ";
$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);