未定义的变量错误,但我想要的是工作正常

时间:2015-09-05 00:29:37

标签: php mysql sql

我收到Undefined变量错误,但一切正常。 我想要做的是前10名比赛获胜者的输出,它适用于此代码,但显示$ ID的未定义变量 这是代码

<?php
$query = $koneksi->prepare("SELECT `user`, `RaceWon` FROM `pdata` WHERE `banned`=0 ORDER BY `RaceWon` DESC LIMIT 10");
$query->execute();
if($query->rowCount() == 0)
{
    echo "<tr><td colspan='6'><small>No rows found</small></td></tr>";
}
while($data = $query->fetch())
{
    $ID++; //<- Undefined variable but the function works what i wanted
    echo "<tr><td>".$ID."</td>";
    echo "<td>".$data['user']."</td>";
    echo "<td>".$data['RaceWon']."</td></tr>";
}
?>

任何帮助将不胜感激.. 感谢

2 个答案:

答案 0 :(得分:4)

你需要在循环之前初始化$ID

$ID = 0;
while ($data = $query->fetch())
{
    $ID++;
    ...
}

无论如何它都有用,因为当您尝试将单位化变量用作数字时,它会自动转换为0。但它仍会打印警告,因为它最初是未定义的。

答案 1 :(得分:3)

试试这个:

<?php
$query = $koneksi->prepare("SELECT `user`, `RaceWon` FROM `pdata` WHERE `banned`=0 ORDER BY `RaceWon` DESC LIMIT 10");
$query->execute();
if($query->rowCount() == 0)
{
    echo "<tr><td colspan='6'><small>No rows found</small></td></tr>";
}
$ID = 0;
while($data = $query->fetch())
{
    $ID++; //<- Undefined variable but the function works what i wanted
    echo "<tr><td>".$ID."</td>";
    echo "<td>".$data['user']."</td>";
    echo "<td>".$data['RaceWon']."</td></tr>";
}
?>