0

如何在 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%')
4

6 回答 6

4

foreach 不需要:

<?
$output = Array ( 'intel', 'amd' );
$Query = echo 'select * from laptop where processor LIKE \'%'.join($output,'%\' OR processor LIKE \'%').'\'%';
?>

希望这可以帮助

于 2013-09-27T12:21:26.190 回答
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;
于 2013-09-27T12:07:34.397 回答
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);


?>

工作代码

于 2013-09-27T12:09:46.233 回答
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;
于 2013-09-27T12:11:46.473 回答
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;
于 2013-09-27T12:13:37.137 回答
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;
于 2013-09-27T12:15:39.013 回答