php - mysql 查询在 for 循环中给出不正确的结果

标签 php mysql

下面的代码只给了我 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>";

?>

while select 语句

select Distinct Country from trendsmtable where WHORegionAC='Europe - all countries'

当我在 mysql 中执行它时返回 22 行,这是正确的!

请帮我找出错误。

最佳答案

嗯,你有一个额外的 $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>';

关于php - mysql 查询在 for 循环中给出不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6798352/

相关文章:

mysql - 如何设计一个简单的数据库

PHP ssh2_auth_pubkey_file() : Authentication failed using public key: Invalid key data, 不是 base64 编码

php - Composer 冲突和 Symfony 3

PHP file_put_contents() 错误

调用不同 SELECT 语句的 MySQL IF/CASE 语法

mysql - SQL 财政季度总计...我已经有了日历的

php - 如何将分钟添加到日期时间字段然后选择 mysql 中的所有匹配项?

javascript - 如何使这种登录/重定向方法更安全

php - 如何检索每一行的 ID,然后将其分配给链接

mysql - 带有 IN 子句的依赖子查询