Use an Array to Cycle Through a MySQL Where Statement
Posted
by Ryan
on Stack Overflow
See other posts from Stack Overflow
or by Ryan
Published on 2010-05-23T16:23:12Z
Indexed on
2010/05/23
16:31 UTC
Read the original article
Hit count: 327
I'm trying to create a loop that will output multiple where statements for a MySQL query. Ultimately, my goal is to end up with these four separate Where statements:
`fruit` = '1' AND `vegetables` = '1'
`fruit` = '1' AND `vegetables` = '2'
`fruit` = '2' AND `vegetables` = '1'
`fruit` = '2' AND `vegetables` = '2'
My theoretical code is pasted below:
<?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++;
}
?>
When I run this code, I get the following output:
`fruit` = '1' AND `vegetables` = '1'
`fruit` = '1' AND `vegetables` = '1' AND `vegetables` = '2'
`fruit` = '1' AND `vegetables` = '1' AND `vegetables` = '2' AND `vegetables` = ''
Does anyone see what I am doing incorrectly? Thanks.
© Stack Overflow or respective owner