如何在php foreach循环中编写mysql where子句。这是我的代码
$outPut = Array ( [0] => 'intel' [1] => 'amd' );
$Query = select * from laptop
foreach($outPut as $Filtervalues)
{
$Query .= "where processor like '%$Filtervalues%'";
}
echo $Query;
但我的输出不正确。
我希望输出为
select * from laptop where (processor like '%intel%' or processor like '%amd%')
答案 0 :(得分:4)
不需要foreach:
<?
$output = Array ( 'intel', 'amd' );
$Query = echo 'select * from laptop where processor LIKE \'%'.join($output,'%\' OR processor LIKE \'%').'\'%';
?>
希望这有帮助
答案 1 :(得分:1)
试试这个
$counter = 0;
$output = Array ( [0] => 'intel' [1] => 'amd' );
$Query = "select * from laptop ";
if(count($output) > 0)
$Query .= " where ( ";
foreach($outPut as $Filtervalues)
{
$counter++;
$Query .= "processor like '%$Filtervalues%'";
if($counter != count($output))
$Query .= " or ";
else
$Query .= ")";
}
echo $Query;
答案 2 :(得分:1)
试试这个:
<?php
$output = Array ( 'intel' , 'amd' );
$Query = 'select * from laptop where ';
foreach($output as $Filtervalues)
{
$whereQuery .= "processor like '%".$Filtervalues."%' OR ";
}
echo $Query . substr($whereQuery, 0, -3);
?>
答案 3 :(得分:1)
您必须仅为第一个过滤器参数添加WHERE
子句:
$output = Array ( 'intel', 'amd' );
$Query = select * from laptop
$firsttime=true;
foreach($output as $Filtervalues)
{
if($firsttime){
$Query .= "where";
$firsttime=false;
}
else
$Query .= "or";
$Query .= " processor like '%Filtervalues%' ";
}
echo $Query;
答案 4 :(得分:1)
您可以将所有条件添加到数组中,稍后再加入其元素。
$output = array ( 'intel', 'amd' );
$Query = 'select * from laptop';
$likes = array();
foreach($output as $Filtervalues)
{
$likes[] = "processor like '%$Filtervalues%'";
}
if(!empty($likes))
$Query .= ' where ('.implode(' or ', $likes) . ')';
echo $Query;
答案 5 :(得分:1)
尝试以下方法:
$output = Array ( 'intel', 'amd' );
$Query = "select * from laptop ";
if(count($output)>0){
$Query .= "WHERE";
foreach($output as $Filtervalues){
$Query .= " processor like '%$Filtervalues%' OR";
}
$Query = trim($Query, " OR");
}
echo $Query;