下面的代码只给我18条记录
<?php
$result4 = mysql_query("select Distinct Country from trendsmtable where WHORegionAC='Europe - all countries' GROUP BY Country ");
echo "<table width=880 align=center>";
echo "<tr><td colspan=4 style='font-family:Arial;'><b>European Region</b></td></tr>";
$num_columns4 = 4;
$num_rows4 = mysql_num_rows($result4);
$i=0;
while($row4 = mysql_fetch_assoc($result4)){
$results[$i] = $row4['Country'];
$i++;
}
unset($i);
$k=0;
for ($i=0;$i<=($num_rows4/($num_columns4+1));$i++){
echo '<tr>';
for($j=1;$j<=$num_columns4;$j++){
echo "<td width=220 style='font-family:Arial; font-size:12px'>".$results[$k].'</td>';
$k++;
}
echo '</tr>';
$k++;
}
echo "</table>";
?>
而select语句
从trendmtable中选择Distinct Country WHORegionAC ='Europe - 所有国家的
返回22行,而我在mysql中执行它是正确的!
请帮我找到错误。
答案 0 :(得分:3)
嗯,你有一个额外的$ k ++,你不需要:
$k++; // keep this one
}
echo '</tr>';
$k++; // remove this one
}
我已经完成了你的代码并且我做了一些编辑。希望他们一路上能清理你的问题:
// got rid of group by. With a select distinct, it isn't necessary
$result4 = mysql_query("select Distinct Country from trendsmtable where ".
"WHORegionAC='Europe - all countries'");
// a good practice is to always double-quote your HTML attributes.
echo "<table width=\"880\" align=\"center\">";
echo "<tr><td colspan=4 style=\"font-family:Arial;\">".
"<b>European Region</b></td></tr>";
$num_columns4 = 4; // where does 4 come from.
// $results was never initialized before.
$results = array();
while($row4 = mysql_fetch_assoc($result4)){
// This is generally thought of as "cleaner" than using an index.
// And since there cannot be more than, say, 220 rows, cleanliness
// should be a high-priority standard.
$results[] = $row4['Country'];
}
// mysql_num_rows rarely provides any major benefit at all.
$num_rows4 = count($results);
foreach( $results as $key => $val )
{
// This happens every time we fill all columns and need a new row.
if( !( $key % $num_columns4 ) )
{
// makes it so that after the first time this closes the prev
// row before starting a new one.
if( $key ) echo '</tr>';
echo '<tr>';
}
// insert nag about CSS
echo '<td width="220" style="font-family:Arial; font-size:12px">'.
$val.
'</td>';
}
echo '</tr></table>';
答案 1 :(得分:0)
我认为PHP看起来有点奇怪,看起来你正在从0循环到(22/5) 然后在内循环中4次。
group by
select distinct
不应该有任何区别
答案 2 :(得分:-1)
PHP文件中的SQL代码包含GROUP BY
子句,如果数据库中有多个国家/地区,则可以减少返回的行数。