2

我的 mysql 查询有问题,我需要从我的表中提取所有数据并将他用作另一个 sql 查询。

这是我正在使用的代码:

<?php
function toateMhz() {

 require ('SQL.php');
     $sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
     foreach ($dbh->query($sql) as $linie)  
     {
     $mhz[] = $linie['performanta_cpu'];
     }

     if(isset($mhz['1']))
    {
    $mhz1 = "$mhz[0] OR ";
}    
    else $mhz['0'];

     if(isset($mhz['2']))
    {
    $mhz2 = "$mhz[1] OR ";
}    
    else $mhz['1'];

     if(isset($mhz['3']))
    {
    $mhz3 = "$mhz[2] OR ";
}    
    else $mhz['2'];

     if(isset($mhz['4']))
    {
    $mhz4 = "$mhz[3] OR ";
}    
    else $mhz['3'];

     if(isset($mhz['5']))
    {
    $mhz5 = "$mhz[4] OR ";
}    
    else $mhz['4'];

     if(isset($mhz['6']))
    {
    $mhz6 = "$mhz[5] OR ";
}    
    else $mhz['5'];

     if(isset($mhz['7']))
    {
    $mhz7 = "$mhz[6] OR ";
}    
    else $mhz['6'];

     if(isset($mhz['8']))
    {
    $mhz8 = "$mhz[7] OR ";
}    
    else $mhz['7'];

     if(isset($mhz['9']))
    {
    $mhz9 = "$mhz[8] OR ";
}    
    else $mhz['8'];

     if(isset($mhz['10']))
    {
    $mhz10 = "$mhz[9] OR ";
}    
    else $mhz['9'];

     if(isset($mhz['11']))
    {
    $mhz11 = "$mhz[10] OR ";
}    
    else $mhz['10'];

     if(isset($mhz['12']))
    {
    $mhz12 = "$mhz[11] OR ";
}    
    else $mhz['11'];

     if(isset($mhz['13']))
    {
    $mhz13 = "$mhz[12] OR ";
}    
    else $mhz['12'];

     if(isset($mhz['14']))
    {
    $mhz14 = "$mhz[13] OR ";
}    
    else $mhz['13'];

    if(isset($mhz['15']))
    {
    $mhz14 = "$mhz[14] OR ";
}    
    else $mhz['14'];

    $frecvente = "$mhz1 $mhz2 $mhz3 $mhz4 $mhz5 $mhz6 $mhz7 $mhz8 $mhz9 $mhz10 $mhz11 $mhz12 $mhz13 $mhz14";
    return $frecvente;
}

 echo toateMhz();   
?>

这是代码的结果:

2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR

但正确的结果是2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR 200

最后一句话不能OR

4

2 回答 2

3

不太确定,但这可能会奏效

foreach ($dbh->query($sql) as $linie) {
    // append value of this record to the array $mhz
    $mhz[] = $linie['performanta_cpu'];
}
// return the concatenation of all elements in $mhz with ' OR ' as "glue" between elements
return join(' OR ', $mhz);

join($s, $arr)是一个别名,implode($s, $arr)它连接给定数组 $arr 的所有(字符串)元素并将 $s 放在元素“之间”。例如

$x = array('a','b', 'c');
echo join(' - ', $x);

印刷a - b - c

于 2013-03-06T16:05:22.707 回答
2

使用 implode 将数组值加入字符串:

function toateMhz() {

    require ('SQL.php');
    $sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
    foreach ($dbh->query($sql) as $linie)  
    {
        $mhz[] = $linie['performanta_cpu'];
    }
    return implode(" OR ", $mzh);
}
echo toateMhz(); 
于 2013-03-06T16:05:43.753 回答