我有一个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
答案 0 :(得分: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“放在”元素之间。 E.g。
$x = array('a','b', 'c');
echo join(' - ', $x);
打印a - b - c
答案 1 :(得分: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();