我正在使用以下代码从数据库中获取行
$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个条目。
我如何进行预测?数组,所以我不必继续写出来。
提前致谢
答案 0 :(得分: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, '%')))
<强> Codepad 强>
答案 1 :(得分: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());
答案 2 :(得分: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());
答案 3 :(得分:0)
最好使用不同的方法(mysql_query是'老方法':mysql_*
函数是deprecated in 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());