0

我正在使用以下代码从数据库中获取行

$get_brand_filter_result = mysql_query("SELECT * FROM brand WHERE ('$arrBrands[0]'     LIKE CONCAT(brand_name, '%')
OR '$arrBrands[1]' LIKE CONCAT(brand_name, '%')
OR '$arrBrands[2]' LIKE CONCAT(brand_name, '%')
OR '$arrBrands[3]' LIKE CONCAT(brand_name, '%')
OR '$arrBrands[4]' LIKE CONCAT(brand_name, '%')
OR '$arrBrands[5]' LIKE CONCAT(brand_name, '%')
OR '$arrBrands[6]' LIKE CONCAT(brand_name, '%')
OR '$arrBrands[7]' LIKE CONCAT(brand_name, '%')
OR '$arrBrands[8]' LIKE CONCAT(brand_name, '%')
)", $db2) or die(mysql_error());

如您所见,我必须手动列出 $arrBrands 中保存的数组元素。问题是数组可以有多达 500 个条目。

我该如何展开?数组,所以我不必一直写出来。

提前致谢

4

4 回答 4

0

尝试这个:

$str    = "";
$apn    = ' OR ';
foreach( $arrBrands as $key => $each ){
    $str    .= "('{$each}' LIKE CONCAT(brand_name, '%')".$apn;
}
$str    = substr( $str, 0, strlen( $str )-3 );
$get_brand_filter_result = mysql_query("SELECT * FROM brand WHERE {$str}", $db2) or die(mysql_error());
于 2013-09-18T09:13:38.347 回答
0

最好使用不同的方法(mysql_query 是一种“旧方法”:mysql_*函数在 PHP 5.5 中已弃用),但您可以在数组上循环(代码未测试):

$q ="SELECT * FROM brand ";
reset($arrBrands);
$lOr=false;
while(list($key,$brand)=each($arrBrands)) {
    $q.=($lOr?" OR ":" WHERE ")."'$brand' LIKE CONCAT(brand_name, '%') ";
    $lOr=true;
}
$get_brand_filter_result = mysql_query($q, $db2) or die(mysql_error());
于 2013-09-18T09:14:12.133 回答
0

你可以试试这样的...

$array = array('puma', 'adidas', 'nike', 'reebok');
$condition = implode("' LIKE CONCAT(brand_name, '%')) OR ('", $array);
$query = "SELECT * FROM brand WHERE (('$condition' LIKE CONCAT(brand_name, '%')));";

// SELECT * FROM brand WHERE (('puma' LIKE CONCAT(brand_name, '%')) OR ('adidas' LIKE CONCAT(brand_name, '%')) OR ('nike' LIKE CONCAT(brand_name, '%')) OR ('reebok' LIKE CONCAT(brand_name, '%')))

键盘

于 2013-09-18T09:09:59.103 回答
0

请使用以下代码。

$count = count($arrBrands);
$seperator = ''
foreach($i=0;$i<$count;$i++)
{
    $sql_part = $seperator."'$arrBrands[".$i."]' LIKE CONCAT(brand_name, '%')";
    $seperator  = ' OR '
}
$get_brand_filter_result = mysql_query("SELECT * FROM brand WHERE $sql_part)", $db2) or die(mysql_error());
于 2013-09-18T09:11:20.747 回答